<pre class=metadata>
Title: Web Audio API 1.1
Shortname: webaudio
Level: 1.1
Group: audiowg
Status: ED
Prepare for TR: no
ED: https://webaudio.github.io/web-audio-api/
TR: https://www.w3.org/TR/webaudio-1.1/
Favicon: favicon.png
Previous Version: https://www.w3.org/TR/2024/WD-webaudio-1.1-20241105/
Previous Version: https://www.w3.org/TR/2021/REC-webaudio-20210617/
Previous Version: https://www.w3.org/TR/2021/CR-webaudio-20210114/
Previous Version: https://www.w3.org/TR/2020/CR-webaudio-20200611/
Previous Version: https://www.w3.org/TR/2018/CR-webaudio-20180918/
Previous Version: https://www.w3.org/TR/2018/WD-webaudio-20180619/
Previous Version: https://www.w3.org/TR/2015/WD-webaudio-20151208/
Previous Version: https://www.w3.org/TR/2013/WD-webaudio-20131010/
Previous Version: https://www.w3.org/TR/2012/WD-webaudio-20121213/
Previous Version: https://www.w3.org/TR/2012/WD-webaudio-20120802/
Previous Version: https://www.w3.org/TR/2012/WD-webaudio-20120315/
Previous Version: https://www.w3.org/TR/2011/WD-webaudio-20111215/
Editor: Paul Adenot, Mozilla (https://www.mozilla.org/), padenot@mozilla.com, w3cid 62410
Editor: Hongchan Choi, Google (https://www.google.com/), hongchan@google.com, w3cid 74103
Former Editor: Raymond Toy (until Oct 2018)
Former Editor: Chris Wilson (Until Jan 2016)
Former Editor: Chris Rogers (Until Aug 2013)
Test Suite: https://github.com/web-platform-tests/wpt/tree/master/webaudio
Repository: WebAudio/web-audio-api
Abstract: This specification describes a high-level Web <abbr title="Application Programming Interface">API</abbr>
    for processing and synthesizing audio in web applications.
    The primary paradigm is of an audio routing graph,
    where a number of {{AudioNode}} objects are connected together to define the overall audio rendering.
    The actual processing will primarily take place in the underlying implementation
    (typically optimized Assembly / C / C++ code),
    but [[#AudioWorklet|direct script processing and synthesis]] is also supported.

    The [[#introductory]] section covers the motivation behind this specification.

    This API is designed to be used in conjunction with other APIs and elements on the web platform, notably:
    XMLHttpRequest [[XHR]] (using the <code>responseType</code> and <code>response</code> attributes).
    For games and interactive applications,
    it is anticipated to be used with the <code>canvas</code> 2D [[2dcontext]]
    and WebGL [[WEBGL]] 3D graphics APIs.
Markup Shorthands: markdown on, dfn on, css off
</pre>

<pre class=anchors>
spec: ECMAScript; url: https://tc39.github.io/ecma262/#sec-data-blocks; type: dfn; text: data block;
url: https://www.w3.org/TR/mediacapture-streams/#dom-mediadevices-getusermedia; type: method; for: MediaDevices; text: getUserMedia()
</pre>
<!-- We want {{object}} and {{Promise}} to go to the WebIDL object -->
<pre class=link-defaults>
spec:webidl; type:interface; text:object
spec:webidl; type:interface; text:Promise
</pre>
<script>
// Handles the loading task for MathJax library.
window.addEventListener('DOMContentLoaded', () => {
    'use strict';
    new Promise((resolve, reject) => {
        let mathjaxScriptEl = document.createElement('script');
        const url = 'https://www.w3.org/scripts/MathJax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
        // TODO: Remove this when Safari supports the onload event; it doesn't
        // support onload event on the script element so we have to poll.
        let id = setInterval(() => {
            if (window.MathJax) {
                clearInterval(id);
                resolve();
            }
        }, 100);
        mathjaxScriptEl.onload = () => {
            clearInterval(id);
            resolve();
            console.log('MathJax loader script: loaded successfully.');
        };
        mathjaxScriptEl.onerror = (error) => {
            const errorEvent = (error instanceof Event)
                ? new Error(error.message) : error;
            reject(errorEvent);
        };
        // Time out after 20 seconds and reject.
        setTimeout(() => {
            mathjaxScriptEl.onerror(
                new Error('MathJax loader script: loading timed out.'));
        }, 20000);
        mathjaxScriptEl.id = 'mathjax';
        mathjaxScriptEl.src = url;
        document.body.appendChild(mathjaxScriptEl);
        console.log('MathJax loader script: started loading... (' + url + ')');
    }).then(() => {
        MathJax.Hub.Config({
            tex2jax: {
                skipTags: ["script", "noscript", "style", "textarea", "code"]
            }
        });
    }).catch((error) => {
        console.error(error);
    });
});
</script>
<style>
@media (prefers-color-scheme: light) {
:root {
    --div-info-fg-color: #178217;
}
}
@media (prefers-color-scheme: dark) {
:root {
    --div-info-fg-color: springgreen;
}
}
.todo {
    border: 1px solid red;
    background-color: rgba(255, 0, 0, 0.3);
}
.todo:before {
    content: "TODO:";
}
.synchronous:before {
    content: "⌛ ";
}
.synchronous:hover{
    border-bottom: 1px dotted gray;
}
body#respecDocument {
    max-width: 60em;
}
.seclist > p {
    font-style: italic;
}
table.channels {
    width:100%;
    overflow: auto;
    margin: 0;
    font-size: 14px;
    font-family: /*Consolas, Monaco,*/ monospace;
}
table.channels th {
    width:60px;
    text-align:center;
}
table.channels td {
    width:60px;
    text-align:center;
}
@media (prefers-color-scheme: light) {
table.channels tr:nth-child(even) {
    background: #EEE;
}
table.channels tr:nth-child(odd) {
    background: #FFF;
}
}
@media (prefers-color-scheme: dark) {
table.channels tr:nth-child(even) {
    background: var(--assertion-border)
}
}

div.node-info {
    padding-left: 4em;
    padding-right: 4em;
}
div.node-info > table {
    border-collapse: collapse;
    border-top: 2px solid #707070;
    border-bottom: 2px solid #707070;
    width: 100%;
    margin: 2em 0;
}
div.node-info > table > tbody > tr > th,
div.node-info > table > tbody > tr > td {
    padding: 0.2em 0.6em;
    min-width: 150px;
    border-top: 1px solid #ddd
}
div.node-info > table > thead > tr > th {
    line-height: 2em;
    font-weight: 600;
    border-bottom: 1px solid #707070;
    color: var(--div-info-fg-color);
}
div.audioparam-info {
    padding-left: 4em;
    padding-right: 4em;
}
div.audioparam-info > table {
    border-collapse: collapse;
    border-top: 2px solid #707070;
    border-bottom: 2px solid #707070;
    width: 100%;
    margin: 2em 0;
}
div.audioparam-info > table > tbody > tr > th,
div.audioparam-info > table > tbody > tr > td {
    padding: 0.2em 0.6em;
    min-width: 150px;
    border-top: 1px solid #ddd
}
div.audioparam-info > table > thead > tr > th {
    line-height: 2em;
    font-weight: 600;
    border-bottom: 1px solid #707070;
    color: var(--div-info-fg-color);
}
div.enum-description > table {
    border-collapse: collapse;
    border-top: 2px solid #707070;
    border-bottom: 2px solid #707070;
    width: 100%;
    margin: 2em 0;
}
div.enum-description > table > tbody > tr > th,
div.enum-description > table > tbody > tr > td {
    padding: 0.2em 0.6em;
    min-width: 150px;
    border-top: 1px solid #ddd
}
div.enum-description > table > thead > tr > th {
    line-height: 2em;
    font-weight: 600;
    color: var(--div-info-fg-color);
    border-bottom: 1px solid #707070;
}
code.nobreak {
  white-space: nowrap;
}
.amendment.proposed, 
.correction.proposed,
.addition.proposed {
    border-width: 0.2em;
    border-radius: 0.4em;
}
.amendment.proposed ins,
.correction.proposed ins,
.addition.proposed ins,
ins[cite].proposed {
    text-decoration: none;
}
.amendment.proposed del,
.correction.proposed del,
.addition.proposed del,
del[cite].proposed {
    color: #cc0000;
    text-decoration-style: solid !important;
    text-decoration-color: #330099;
}
.amendment-buttons {
    margin-bottom: 2em;
    padding: 1em 0em;
    border-bottom: 1px dashed #330099;
}
</style>

<h2 id="introductory" class=no-num>
Introduction</h2>

Audio on the web has been fairly primitive up to this point and until
very recently has had to be delivered through plugins such as Flash and
QuickTime. The introduction of the <{audio}> element in HTML5
is very important, allowing for basic streaming audio playback. But, it
is not powerful enough to handle more complex audio applications. For
sophisticated web-based games or interactive applications, another
solution is required. It is a goal of this specification to include the
capabilities found in modern game audio engines as well as some of the
mixing, processing, and filtering tasks that are found in modern
desktop audio production applications.

The APIs have been designed with a wide variety of use cases
[[webaudio-usecases]] in mind. Ideally, it should be able to support
<i>any</i> use case which could reasonably be implemented with an
optimized C++ engine controlled via script and run in a browser. That
said, modern desktop audio software can have very advanced
capabilities, some of which would be difficult or impossible to build
with this system. Apple's Logic Audio is one such application which has
support for external MIDI controllers, arbitrary plugin audio effects
and synthesizers, highly optimized direct-to-disk audio file
reading/writing, tightly integrated time-stretching, and so on.
Nevertheless, the proposed system will be quite capable of supporting a
large range of reasonably complex games and interactive applications,
including musical ones. And it can be a very good complement to the
more advanced graphics features offered by WebGL. The API has been
designed so that more advanced capabilities can be added at a later
time.

<h3 id="Features">
Features</h3>

The API supports these primary features:

* [[#ModularRouting|Modular routing]] for simple or complex
    mixing/effect architectures.

* High dynamic range, using 32-bit floats for internal processing.

* [[#AudioParam|Sample-accurate scheduled sound playback]]
    with low [[#latency|latency]] for musical applications
    requiring a very high degree of rhythmic precision such as drum
    machines and sequencers. This also includes the possibility of
    [[#DynamicLifetime|dynamic creation]] of effects.

* Automation of audio parameters for envelopes, fade-ins /
    fade-outs, granular effects, filter sweeps, LFOs etc.

* Flexible handling of channels in an audio stream, allowing them
    to be split and merged.

* Processing of audio sources from an <{audio}> or <{video}>
    {{MediaElementAudioSourceNode|media element}}.

* Processing live audio input using a {{MediaStreamTrackAudioSourceNode|MediaStream}} from
    {{getUserMedia()}}.

* Integration with WebRTC
    * Processing audio received from a remote peer using a
        {{MediaStreamTrackAudioSourceNode}} and
        [[!webrtc]].

    * Sending a generated or processed audio stream to a remote
        peer using a {{MediaStreamAudioDestinationNode}}
        and [[!webrtc]].

* Audio stream synthesis and processing [[#AudioWorklet|directly using scripts]].

* [[#Spatialization|Spatialized audio]] supporting a wide
    range of 3D games and immersive environments:

    * Panning models: equalpower, HRTF, pass-through
    * Distance Attenuation
    * Sound Cones
    * Obstruction / Occlusion
    * Source / Listener based

* A convolution engine for a wide
    range of linear effects, especially very high-quality room effects.
    Here are some examples of possible effects:

    * Small / large room
    * Cathedral
    * Concert hall
    * Cave
    * Tunnel
    * Hallway
    * Forest
    * Amphitheater
    * Sound of a distant room through a doorway
    * Extreme filters
    * Strange backwards effects
    * Extreme comb filter effects

* Dynamics compression for overall control and sweetening of the mix

* Efficient [[#AnalyserNode|real-time time-domain and frequency-domain analysis / music visualizer support]].

* Efficient biquad filters for lowpass, highpass, and other common filters.

* A Waveshaping effect for distortion and other non-linear effects

* Oscillators

<h4 id="ModularRouting">
Modular Routing</h4>

Modular routing allows arbitrary connections between different
{{AudioNode}} objects. Each node can have
<dfn>inputs</dfn> and/or <dfn>outputs</dfn>.
A <dfn>source node</dfn> has no inputs and a single output.
A <dfn>destination node</dfn> has one input and no outputs. Other nodes such as
filters can be placed between the source and destination nodes. The
developer doesn't have to worry about low-level stream format
details when two objects are connected together;
<a href="#channel-up-mixing-and-down-mixing">the right thing just happens</a>.
For example, if a mono audio stream is connected to a
stereo input it should just mix to left and right channels
[[#channel-up-mixing-and-down-mixing|appropriately]].

In the simplest case, a single source can be routed directly to the output.
All routing occurs within an {{AudioContext}}
containing a single {{AudioDestinationNode}}:

<figure>
    <img alt="modular routing" src="images/modular-routing1.png" width="305" height="128">
    <figcaption>
        A simple example of modular routing.
    </figcaption>
</figure>

Illustrating this simple routing, here's a simple example playing a single sound:

<pre class="example" highlight="js">
const context = new AudioContext();

function playSound() {
    const source = context.createBufferSource();
    source.buffer = dogBarkingBuffer;
    source.connect(context.destination);
    source.start(0);
}
</pre>

Here's a more complex example with three sources and a convolution
reverb send with a dynamics compressor at the final output stage:

<figure>
    <img alt="modular routing2" src="images/modular-routing2.png" width="561" height="411">
    <figcaption>
        A more complex example of modular routing.
    </figcaption>
</figure>

<pre class="example" highlight="js" line-numbers>
let context;
let compressor;
let reverb;

let source1, source2, source3;

let lowpassFilter;
let waveShaper;
let panner;

let dry1, dry2, dry3;
let wet1, wet2, wet3;

let mainDry;
let mainWet;

function setupRoutingGraph () {
    context = new AudioContext();

    // Create the effects nodes.
    lowpassFilter = context.createBiquadFilter();
    waveShaper = context.createWaveShaper();
    panner = context.createPanner();
    compressor = context.createDynamicsCompressor();
    reverb = context.createConvolver();

    // Create main wet and dry.
    mainDry = context.createGain();
    mainWet = context.createGain();

    // Connect final compressor to final destination.
    compressor.connect(context.destination);

    // Connect main dry and wet to compressor.
    mainDry.connect(compressor);
    mainWet.connect(compressor);

    // Connect reverb to main wet.
    reverb.connect(mainWet);

    // Create a few sources.
    source1 = context.createBufferSource();
    source2 = context.createBufferSource();
    source3 = context.createOscillator();

    source1.buffer = manTalkingBuffer;
    source2.buffer = footstepsBuffer;
    source3.frequency.value = 440;

    // Connect source1
    dry1 = context.createGain();
    wet1 = context.createGain();
    source1.connect(lowpassFilter);
    lowpassFilter.connect(dry1);
    lowpassFilter.connect(wet1);
    dry1.connect(mainDry);
    wet1.connect(reverb);

    // Connect source2
    dry2 = context.createGain();
    wet2 = context.createGain();
    source2.connect(waveShaper);
    waveShaper.connect(dry2);
    waveShaper.connect(wet2);
    dry2.connect(mainDry);
    wet2.connect(reverb);

    // Connect source3
    dry3 = context.createGain();
    wet3 = context.createGain();
    source3.connect(panner);
    panner.connect(dry3);
    panner.connect(wet3);
    dry3.connect(mainDry);
    wet3.connect(reverb);

    // Start the sources now.
    source1.start(0);
    source2.start(0);
    source3.start(0);
}
</pre>

Modular routing also permits the output of
{{AudioNode}}s to be routed to an
{{AudioParam}} parameter that controls the behavior
of a different {{AudioNode}}. In this scenario, the
output of a node can act as a modulation signal rather than an
input signal.

<figure>
    <img alt="modular routing3" src="images/modular-routing3.png"
    width="346" height="337">
    <figcaption>
        Modular routing illustrating one Oscillator modulating the
        frequency of another.
    </figcaption>
</figure>

<pre class="example" highlight="js" line-numbers>
function setupRoutingGraph() {
    const context = new AudioContext();

    // Create the low frequency oscillator that supplies the modulation signal
    const lfo = context.createOscillator();
    lfo.frequency.value = 1.0;

    // Create the high frequency oscillator to be modulated
    const hfo = context.createOscillator();
    hfo.frequency.value = 440.0;

    // Create a gain node whose gain determines the amplitude of the modulation signal
    const modulationGain = context.createGain();
    modulationGain.gain.value = 50;

    // Configure the graph and start the oscillators
    lfo.connect(modulationGain);
    modulationGain.connect(hfo.detune);
    hfo.connect(context.destination);
    hfo.start(0);
    lfo.start(0);
}
</pre>

<h3 id="APIOverview">
API Overview</h3>

The interfaces defined are:

* An <a class="dfnref" href="#AudioContext">AudioContext</a>
    interface, which contains an audio signal graph representing
    connections between {{AudioNode}}s.

* An {{AudioNode}} interface, which represents
    audio sources, audio outputs, and intermediate processing modules.
    {{AudioNode}}s can be dynamically connected together
    in a [[#ModularRouting|modular fashion]].
    {{AudioNode}}s exist in the context of an
    {{AudioContext}}.

* An {{AnalyserNode}} interface, an
    {{AudioNode}} for use with music visualizers, or
    other visualization applications.

* An {{AudioBuffer}} interface, for working with
    memory-resident audio assets. These can represent one-shot sounds, or
    longer audio clips.

* An {{AudioBufferSourceNode}} interface, an
    {{AudioNode}} which generates audio from an
    AudioBuffer.

* An {{AudioDestinationNode}} interface, an
    {{AudioNode}} subclass representing the final
    destination for all rendered audio.

* An {{AudioParam}} interface, for controlling an
    individual aspect of an {{AudioNode}}'s functioning,
    such as volume.

* An {{AudioListener}} interface, which works with
    a {{PannerNode}} for spatialization.

* An {{AudioWorklet}} interface representing a
    factory for creating custom nodes that can process audio directly
    using scripts.

* An {{AudioWorkletGlobalScope}} interface, the
    context in which AudioWorkletProcessor processing scripts run.

* An {{AudioWorkletNode}} interface, an
    {{AudioNode}} representing a node processed in an
    AudioWorkletProcessor.

* An {{AudioWorkletProcessor}} interface,
    representing a single node instance inside an audio worker.

* A {{BiquadFilterNode}} interface, an
    {{AudioNode}} for common low-order filters such as:

    * Low Pass
    * High Pass
    * Band Pass
    * Low Shelf
    * High Shelf
    * Peaking
    * Notch
    * Allpass

* A {{ChannelMergerNode}} interface, an
    {{AudioNode}} for combining channels from multiple
    audio streams into a single audio stream.

* A {{ChannelSplitterNode}} interface, an {{AudioNode}} for accessing the individual channels of an
    audio stream in the routing graph.

* A {{ConstantSourceNode}} interface, an
    {{AudioNode}} for generating a nominally constant output value
    with an {{AudioParam}} to allow automation of the value.

* A {{ConvolverNode}} interface, an
    {{AudioNode}} for applying a
    real-time linear effect (such as the sound of
    a concert hall).

* A {{DelayNode}} interface, an
    {{AudioNode}} which applies a dynamically adjustable
    variable delay.

* A {{DynamicsCompressorNode}} interface, an
    {{AudioNode}} for dynamics compression.

* A {{GainNode}} interface, an
    {{AudioNode}} for explicit gain control.

* An {{IIRFilterNode}} interface, an
    {{AudioNode}} for a general IIR filter.

* A {{MediaElementAudioSourceNode}} interface, an
    {{AudioNode}} which is the audio source from an
    <{audio}>, <{video}>, or other media element.

* A {{MediaStreamAudioSourceNode}} interface, an
    {{AudioNode}} which is the audio source from a
    {{MediaStream}} such as live audio input, or from a remote peer.

* A {{MediaStreamTrackAudioSourceNode}} interface,
    an {{AudioNode}} which is the audio source from a
    {{MediaStreamTrack}}.

* A {{MediaStreamAudioDestinationNode}} interface,
    an {{AudioNode}} which is the audio destination to a
    {{MediaStream}} sent to a remote peer.

* A {{PannerNode}} interface, an
    {{AudioNode}} for spatializing / positioning audio in
    3D space.

* A {{PeriodicWave}} interface for specifying
    custom periodic waveforms for use by the
    {{OscillatorNode}}.

* An {{OscillatorNode}} interface, an
    {{AudioNode}} for generating a periodic waveform.

* A {{StereoPannerNode}} interface, an
    {{AudioNode}} for equal-power positioning of audio
    input in a stereo stream.

* A {{WaveShaperNode}} interface, an
    {{AudioNode}} which applies a non-linear waveshaping
    effect for distortion and other more subtle warming effects.

There are also several features that have been deprecated from the
Web Audio API but not yet removed, pending implementation experience
of their replacements:

* A {{ScriptProcessorNode}} interface, an {{AudioNode}} for generating or processing audio directly
    using scripts.

* An {{AudioProcessingEvent}} interface, which is
    an event type used with {{ScriptProcessorNode}}
    objects.

<h2 id="audioapi">
The Audio API</h2>

<!--
████████     ███     ██████  ████████          ███     ██████
██     ██   ██ ██   ██    ██ ██               ██ ██   ██    ██
██     ██  ██   ██  ██       ██              ██   ██  ██
████████  ██     ██  ██████  ██████         ██     ██ ██
██     ██ █████████       ██ ██             █████████ ██
██     ██ ██     ██ ██    ██ ██             ██     ██ ██    ██
████████  ██     ██  ██████  ████████       ██     ██  ██████
-->

<h3 interface lt="BaseAudioContext" id="BaseAudioContext">
The {{BaseAudioContext}} Interface</h3>

This interface represents a set of {{AudioNode}}
objects and their connections. It allows for arbitrary routing of
signals to an {{AudioDestinationNode}}. Nodes are
created from the context and are then [[#ModularRouting|connected]] together.

{{BaseAudioContext}} is not instantiated directly,
but is instead extended by the concrete interfaces
{{AudioContext}} (for real-time rendering) and
{{OfflineAudioContext}} (for offline rendering).

{{BaseAudioContext}} are created with an internal slot
<dfn attribute for="BaseAudioContext">[[pending promises]]</dfn>  that is an
initially empty ordered list of promises.

Each {{BaseAudioContext}} has a unique
<a href="https://html.spec.whatwg.org/multipage/media.html#media-element-event-task-source">
media element event task source</a>.
Additionally, a {{BaseAudioContext}} has several private slots <dfn attribute
for="BaseAudioContext">[[rendering thread state]]</dfn> and <dfn attribute
for="BaseAudioContext">[[control thread state]]</dfn> that take values
from {{AudioContextState}}, and that are both initially set to <code>"suspended"
</code>, <dfn attribute for="BaseAudioContext">[[state before interruption]]
</dfn> that also take values from {{AudioContextState}} and is initially set to
`null` and a private slot <dfn attribute for="BaseAudioContext">[[render quantum
size]]</dfn> that is an unsigned integer.

<pre class="idl">
enum AudioContextState {
    "suspended",
    "running",
    "closed",
    "interrupted"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-for="AudioContextState" dfn-type="enum-value">
    <caption>{{AudioContextState}} enumeration description</caption>
    <thead>
        <tr>
            <th>Enum value</th><th>Description</th>
    <tbody>
        <tr>
            <td>
                "<dfn>suspended</dfn>"
            <td>
                This context is currently suspended (context time is not
                proceeding, audio hardware may be powered down/released).
        <tr>
            <td>
                "<dfn>running</dfn>"
            <td>
                Audio is being processed.
        <tr>
            <td>
                "<dfn>closed</dfn>"
            <td>
                This context has been released, and can no longer be used to
                process audio. All system audio resources have been released.
        <tr>
            <td>
                "<dfn>interrupted</dfn>"
            <td>
                This context is currently interrupted and cannot process audio
                until the [=interruption=] ends.
</table>
</div>

<pre class="idl">
 enum AudioContextRenderSizeCategory {
    "default",
    "hardware"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-for="AudioContextRenderSizeCategory" dfn-type="enum-value">
    <thead>
        <tr>
            <th scope="col" colspan="2">
                Enumeration description
            </th>
        </tr>
    <tbody>
        <tr>
            <td>
                "<dfn>default</dfn>"
            <td>
                The AudioContext's <a>render quantum size</a> is the default value of 128
                frames.
        <tr>
            <td>
                "<dfn>hardware</dfn>"
            </td>
            <td>
                The User-Agent picks a <a>render quantum size</a> that is best for the
                current configuration.

                Note: This exposes information about the host and can be used for fingerprinting.
            </td>
        </tr>
</table>
</div>

<xmp class="idl">
callback DecodeErrorCallback = undefined (DOMException error);

callback DecodeSuccessCallback = undefined (AudioBuffer decodedData);

[Exposed=Window]
interface BaseAudioContext : EventTarget {
    readonly attribute AudioDestinationNode destination;
    readonly attribute float sampleRate;
    readonly attribute double currentTime;
    readonly attribute AudioListener listener;
    readonly attribute AudioContextState state;
    readonly attribute unsigned long renderQuantumSize;
    [SameObject, SecureContext]
    readonly attribute AudioWorklet audioWorklet;
    attribute EventHandler onstatechange;

    AnalyserNode createAnalyser ();
    BiquadFilterNode createBiquadFilter ();
    AudioBuffer createBuffer (unsigned long numberOfChannels,
                                unsigned long length,
                                float sampleRate);
    AudioBufferSourceNode createBufferSource ();
    ChannelMergerNode createChannelMerger (optional unsigned long numberOfInputs = 6);
    ChannelSplitterNode createChannelSplitter (
        optional unsigned long numberOfOutputs = 6);
    ConstantSourceNode createConstantSource ();
    ConvolverNode createConvolver ();
    DelayNode createDelay (optional double maxDelayTime = 1.0);
    DynamicsCompressorNode createDynamicsCompressor ();
    GainNode createGain ();
    IIRFilterNode createIIRFilter (sequence<double> feedforward,
                                    sequence<double> feedback);
    OscillatorNode createOscillator ();
    PannerNode createPanner ();
    PeriodicWave createPeriodicWave (sequence<float> real,
                                        sequence<float> imag,
                                        optional PeriodicWaveConstraints constraints = {});
    ScriptProcessorNode createScriptProcessor(
        optional unsigned long bufferSize = 0,
        optional unsigned long numberOfInputChannels = 2,
        optional unsigned long numberOfOutputChannels = 2);
    StereoPannerNode createStereoPanner ();
    WaveShaperNode createWaveShaper ();

    Promise<AudioBuffer> decodeAudioData (
        ArrayBuffer audioData,
        optional DecodeSuccessCallback? successCallback,
        optional DecodeErrorCallback? errorCallback);
};
</xmp>

<h4 id='BaseAudioContext-attributes'>
Attributes</h4>

<dl dfn-type=attribute dfn-for=BaseAudioContext>
    : <dfn>audioWorklet</dfn>
    ::
        Allows access to the <code>Worklet</code> object that can import
        a script containing {{AudioWorkletProcessor}}
        class definitions via the algorithms defined by [[!HTML]]
        and {{AudioWorklet}}.

    : <dfn>currentTime</dfn>
    ::
        This is the time in seconds of the sample frame immediately
        following the last sample-frame in the block of audio most
        recently processed by the context's rendering graph. If the
        context's rendering graph has not yet processed a block of
        audio, then {{BaseAudioContext/currentTime}} has a value of
        zero.

        In the time coordinate system of {{BaseAudioContext/currentTime}}, the value of
        zero corresponds to the first sample-frame in the first block
        processed by the graph. Elapsed time in this system corresponds
        to elapsed time in the audio stream generated by the
        {{BaseAudioContext}}, which may not be
        synchronized with other clocks in the system. (For an
        {{OfflineAudioContext}}, since the stream is
        not being actively played by any device, there is not even an
        approximation to real time.)

        All scheduled times in the Web Audio API are relative to the
        value of {{BaseAudioContext/currentTime}}.

        When the {{BaseAudioContext}} is in the
        "{{AudioContextState/running}}" state, the
        value of this attribute is monotonically increasing and is
        updated by the rendering thread in uniform increments,
        corresponding to one <a>render quantum</a>. Thus, for a running
        context, <code>currentTime</code> increases steadily as the
        system processes audio blocks, and always represents the time
        of the start of the next audio block to be processed. It is
        also the earliest possible time when any change scheduled in
        the current state might take effect.

        <code>currentTime</code> MUST be read <a>atomically</a> on the control thread before being
        returned.

    : <dfn>destination</dfn>
    ::
        An {{AudioDestinationNode}}
        with a single input representing the final destination for all
        audio. Usually this will represent the actual audio hardware.
        All {{AudioNode}}s actively rendering audio
        will directly or indirectly connect to {{BaseAudioContext/destination}}.

    : <dfn>listener</dfn>
    ::
        An {{AudioListener}}
        which is used for 3D <a href="#Spatialization">spatialization</a>.

    : <dfn>onstatechange</dfn>
    ::
        A property used to set an [=event handler=] for an
        event that is dispatched to
        {{BaseAudioContext}} when the state of the
        AudioContext has changed (i.e. when the corresponding promise
        would have resolved). The event type of this event handler is
        <dfn event>statechange</dfn>. An event that uses the
        {{Event}} interface will be dispatched to the event
        handler, which can query the AudioContext's state directly. A
        newly-created AudioContext will always begin in the
        <code>suspended</code> state, and a state change event will be
        fired whenever the state changes to a different state. This
        event is fired before the {{complete}} event
        is fired.

    : <dfn>sampleRate</dfn>
    ::
        The sample rate (in sample-frames per second) at which the
        {{BaseAudioContext}} handles audio. It is assumed that all
        {{AudioNode}}s in the context run at this rate. In making this
        assumption, sample-rate converters or "varispeed" processors are
        not supported in real-time processing.
        The <dfn dfn for="/">Nyquist frequency</dfn> is half this sample-rate value.

    : <dfn>state</dfn>
    ::
        Describes the current state of the {{BaseAudioContext}}.  Getting this
        attribute returns the contents of the {{[[control thread state]]}} slot.

    : <dfn>renderQuantumSize</dfn>
    ::
        Getting this attribute returns the value of {{BaseAudioContext/[[render
        quantum size]]}} slot.
</dl>

<h4 id="BaseAudioContent-methods">
Methods</h4>

<dl dfn-type=method dfn-for=BaseAudioContext>
    : <dfn>createAnalyser()</dfn>
    ::
        <a>Factory method</a> for an {{AnalyserNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{AnalyserNode}}
        </div>

    : <dfn>createBiquadFilter()</dfn>
    ::
        <a>Factory method</a> for a {{BiquadFilterNode}}
        representing a second order filter which can be configured as one
        of several common filter types.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{BiquadFilterNode}}
        </div>

    : <dfn>createBuffer(numberOfChannels, length, sampleRate)</dfn>
    ::
        Creates an AudioBuffer of the given size. The audio data in the
        buffer will be zero-initialized (silent).
        <span class="synchronous">A {{NotSupportedError}} exception MUST be
        thrown if any of the arguments is negative, zero, or outside its
        nominal range.</span>

        <pre class=argumentdef for="BaseAudioContext/createBuffer()">
        numberOfChannels: Determines how many channels the buffer will have. An implementation MUST support at least 32 channels.
        length: Determines the size of the buffer in sample-frames.  This MUST be at least 1.
        sampleRate: Describes the sample-rate of the [=linear PCM=] audio data in the buffer in sample-frames per second. An implementation MUST support sample rates in at least the range 8000 to 96000.
        </pre>
        <div>
            <em>Return type:</em> {{AudioBuffer}}
        </div>

    : <dfn>createBufferSource()</dfn>
    ::
        <a>Factory method</a> for a
        {{AudioBufferSourceNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{AudioBufferSourceNode}}
        </div>

    : <dfn>createChannelMerger(numberOfInputs)</dfn>
    ::
        <a>Factory method</a> for a
        {{ChannelMergerNode}} representing a channel
        merger. <span class="synchronous">An
        {{IndexSizeError}} exception MUST be thrown if
        {{BaseAudioContext/createChannelMerger(numberOfInputs)/numberOfInputs}} is less than 1 or is greater than the number of supported channels.</span>

        <pre class=argumentdef for="BaseAudioContext/createChannelMerger(numberOfInputs)">
        numberOfInputs: Determines the number of inputs. Values of up to 32 MUST be supported. If not specified, then `6` will be used.
        </pre>

        <div>
            <em>Return type:</em> {{ChannelMergerNode}}
        </div>

    : <dfn>createChannelSplitter(numberOfOutputs)</dfn>
    ::
        <a>Factory method</a> for a
        {{ChannelSplitterNode}} representing a channel
        splitter. <span class="synchronous">An
        {{IndexSizeError}} exception MUST be thrown if
        {{BaseAudioContext/createChannelSplitter(numberOfOutputs)/numberOfOutputs}}  is less than 1 or is greater than the number of supported channels.</span>

        <pre class=argumentdef for="BaseAudioContext/createChannelSplitter(numberOfOutputs)">
        numberOfOutputs: The number of outputs. Values of up to 32 MUST be supported. If not specified, then `6` will be used.
        </pre>

        <div>
            <em>Return type:</em> {{ChannelSplitterNode}}
        </div>

    : <dfn>createConstantSource()</dfn>
    ::
        <a>Factory method</a> for a
        {{ConstantSourceNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{ConstantSourceNode}}
        </div>

    : <dfn>createConvolver()</dfn>
    ::
        <a>Factory method</a> for a {{ConvolverNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{ConvolverNode}}
        </div>

    : <dfn>createDelay(maxDelayTime)</dfn>
    ::
        <a>Factory method</a> for a {{DelayNode}}. The initial default
        delay time will be 0 seconds.

        <pre class=argumentdef for="BaseAudioContext/createDelay(maxDelayTime)">
        maxDelayTime: Specifies the maximum delay time in seconds allowed for the delay line. <span class="synchronous">If specified, this value MUST be greater than zero and less than three minutes or a {{NotSupportedError}} exception MUST be thrown.</span> If not specified, then `1` will be used.
        </pre>

        <div>
            <em>Return type:</em> {{DelayNode}}
        </div>

    : <dfn>createDynamicsCompressor()</dfn>
    ::
        <a>Factory method</a> for a
        {{DynamicsCompressorNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{DynamicsCompressorNode}}
        </div>

    : <dfn>createGain()</dfn>
    ::
        <a>Factory method</a> for {{GainNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{GainNode}}
        </div>

    : <dfn>createIIRFilter(feedforward, feedback)</dfn>
    ::
        <pre class=argumentdef for="BaseAudioContext/createIIRFilter()">
        feedforward: An array of the feedforward (numerator) coefficients for the transfer function of the IIR filter. The maximum length of this array is 20. If all of the values are zero, <span class="synchronous">an {{InvalidStateError}} <em class="rfc2119" title="MUST">MUST</em> be thrown</span>. <span class="synchronous">A {{NotSupportedError}} <em class="rfc2119" title="MUST">MUST</em> be thrown if the array length is 0 or greater than 20</span>.
        feedback: An array of the feedback (denominator) coefficients for the transfer function of the IIR filter. The maximum length of this array is 20. If the first element of the array is 0, <span class="synchronous">an {{InvalidStateError}} <em class="rfc2119" title="MUST">MUST</em> be thrown</span>. <span class="synchronous">A {{NotSupportedError}} <em class="rfc2119" title="MUST">MUST</em> be thrown if the array length is 0 or greater than 20</span>.
        </pre>

        <div>
            <em>Return type:</em> {{IIRFilterNode}}
        </div>

    : <dfn>createOscillator()</dfn>
    ::
        <a>Factory method</a> for an {{OscillatorNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{OscillatorNode}}
        </div>

    : <dfn>createPanner()</dfn>
    ::
        <a>Factory method</a> for a {{PannerNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{PannerNode}}
        </div>

    : <dfn>createPeriodicWave(real, imag, constraints)</dfn>
    ::
        <a>Factory method</a> to create a
        {{PeriodicWave}}.

        <div algorithm="BaseAudioContext.createPeriodicWave()">
            When calling this method,
            execute these steps:

            1. <span class="synchronous">If {{BaseAudioContext/createPeriodicWave()/real}} and {{BaseAudioContext/createPeriodicWave()/imag}} are not of the same
                length, an {{IndexSizeError}} MUST be thrown.</span>

            2. Let <var>o</var> be a new object of type
                {{PeriodicWaveOptions}}.

            3. Respectively set the {{BaseAudioContext/createPeriodicWave()/real}} and
                {{BaseAudioContext/createPeriodicWave()/imag}} parameters passed to this factory method to
                the attributes of the same name on <var>o</var>.

            4. Set the {{PeriodicWaveConstraints/disableNormalization}} attribute on
                <var>o</var> to the value of the
                {{PeriodicWaveConstraints/disableNormalization}} attribute of the
                <code>constraints</code> attribute passed to the factory
                method.

            5. Construct a new {{PeriodicWave}}
                <var>p</var>, passing the {{BaseAudioContext}} this factory
                method has been called on as a first argument, and
                <var>o</var>.
            6. Return <var>p</var>.
        </div>

        <pre class=argumentdef for="BaseAudioContext/createPeriodicWave()">
        real: A sequence of cosine parameters. See its {{PeriodicWaveOptions/real}} constructor argument for a more detailed description.
        imag: A sequence of sine parameters. See its {{PeriodicWaveOptions/imag}} constructor argument for a more detailed description.
        constraints: If not given, the waveform is normalized. Otherwise, the waveform is normalized according the value given by <code>constraints</code>.
        </pre>

        <div>
            <em>Return type:</em> {{PeriodicWave}}
        </div>

    : <dfn>createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels)</dfn>
    ::
        <a>Factory method</a> for a {{ScriptProcessorNode}}.
        This method is DEPRECATED, as it is intended to be replaced by {{AudioWorkletNode}}.
        Creates a {{ScriptProcessorNode}} for direct audio processing using scripts.
        <span class="synchronous">An {{IndexSizeError}} exception MUST be thrown if
        {{bufferSize!!argument}} or {{numberOfInputChannels}} or {{numberOfOutputChannels}}
        are outside the valid range.</span>

        It is invalid for both {{numberOfInputChannels}} and {{numberOfOutputChannels}} to be zero.
        <span class="synchronous">In this case an {{IndexSizeError}} MUST be thrown.</span>

        <pre class=argumentdef for="BaseAudioContext/createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels)">
        bufferSize: The {{ScriptProcessorNode/bufferSize}} parameter determines the buffer size in units of sample-frames. If it's not passed in, or if the value is 0, then the implementation will choose the best buffer size for the given environment, which will be constant power of 2 throughout the lifetime of the node. Otherwise if the author explicitly specifies the bufferSize, it <em class="rfc2119" title="MUST">MUST</em> be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. This value controls how frequently the {{ScriptProcessorNode/audioprocess}} event is dispatched and how many sample-frames need to be processed each call. Lower values for {{ScriptProcessorNode/bufferSize}} will result in a lower (better) <a href="#latency">latency</a>. Higher values will be necessary to avoid audio breakup and <a href="#audio-glitching">glitches</a>. It is recommended for authors to not specify this buffer size and allow the implementation to pick a good buffer size to balance between <a href="#latency">latency</a> and audio quality. If the value of this parameter is not one of the allowed power-of-2 values listed above, <span class="synchronous">an {{IndexSizeError}} <em class="rfc2119" title="MUST">MUST</em> be thrown</span>.
        numberOfInputChannels: This parameter determines the number of channels for this node's input. The default value is 2. Values of up to 32 must be supported. <span class="synchronous">A {{NotSupportedError}} must be thrown if the number of channels is not supported.</span>
        numberOfOutputChannels: This parameter determines the number of channels for this node's output. The default value is 2. Values of up to 32 must be supported. <span class="synchronous">A {{NotSupportedError}} must be thrown if the number of channels is not supported.</span>
        </pre>

        <div>
            <em>Return type:</em> {{ScriptProcessorNode}}
        </div>

    : <dfn>createStereoPanner()</dfn>
    ::
        <a>Factory method</a> for a {{StereoPannerNode}}.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{StereoPannerNode}}
        </div>

    : <dfn>createWaveShaper()</dfn>
    ::
        <a>Factory method</a> for a {{WaveShaperNode}}
        representing a non-linear distortion.
        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{WaveShaperNode}}
        </div>

    : <dfn>decodeAudioData(audioData, successCallback, errorCallback)</dfn>
    ::
        Asynchronously decodes the audio file data contained in the
        {{ArrayBuffer}}. The {{ArrayBuffer}} can, for
        example, be loaded from an <code>XMLHttpRequest</code>'s
        <code>response</code> attribute after setting the
        <code>responseType</code> to <code>"arraybuffer"</code>. Audio
        file data can be in any of the formats supported by the
        <{audio}> element. The buffer passed to
        {{BaseAudioContext/decodeAudioData()}} has its
        content-type determined by sniffing, as described in
        [[!mimesniff]].

        Although the primary method of interfacing with this function
        is via its promise return value, the callback parameters are
        provided for legacy reasons.

        Encourage implementation to warn authors in case of a corrupted file. It
        isn't possible to throw because this would be a breaking change.
        
        <div class=note>
            Note: If the compressed audio data byte-stream is corrupted but the
            decoding can otherwise proceed, implementations are encouraged to warn
            authors for example via the developer tools.
        </div>

        <div algorithm="decodeAudioData()">
            <span class="synchronous">When <code>decodeAudioData</code> is
            called, the following steps MUST be performed on the control
            thread:</span>

            1. If [=this=]'s [=relevant global object=]'s [=associated Document=] is not [=fully active=] then return [=a promise rejected with=] "{{InvalidStateError}}" {{DOMException}}.

            2. Let <var>promise</var> be a new Promise.

            3. If {{BaseAudioContext/decodeAudioData(audioData, successCallback, errorCallback)/audioData!!argument}} 
                is [=BufferSource/detached=], execute the following steps:

                1. Append <var>promise</var> to {{BaseAudioContext/[[pending promises]]}}.

                2. [=ArrayBuffer/Detach=]
                    the {{BaseAudioContext/decodeAudioData(audioData, successCallback, errorCallback)/audioData!!argument}} {{ArrayBuffer}}.
                    If this operations throws, jump to the step 3. 

                3. Queue a decoding operation to be performed on another thread.

            4. Else, execute the following error steps:

                1. Let <var>error</var> be a {{DataCloneError}}.
                2. Reject <var>promise</var> with <var>error</var>, and remove it from
                    {{BaseAudioContext/[[pending promises]]}}.

                3. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                    Queue a media element task</a> to invoke
                    {{BaseAudioContext/decodeAudioData()/errorCallback!!argument}} with |error|.

            5. Return <var>promise</var>.
        </div>

        <div algorithm="queue a decode operation">
            When queuing a decoding operation to be performed on another
            thread, the following steps MUST happen on a thread that is not
            the <a>control thread</a> nor the <a>rendering thread</a>,
            called the <dfn attribute for=BaseAudioContext>decoding thread</dfn>.

            Note: Multiple {{decoding thread}}s can run in parallel to
            service multiple calls to <code>decodeAudioData</code>.

            1. Let <var>can decode</var> be a boolean flag, initially set to true.

            2. Attempt to determine the MIME type of
                {{BaseAudioContext/decodeAudioData(audioData, successCallback,
                errorCallback)/audioData!!argument}}, using
                [[mimesniff#matching-an-audio-or-video-type-pattern]]. If the audio or
                video type pattern matching algorithm returns {{undefined}},
                set <var>can decode</var> to <em>false</em>.

            3. If <var>can decode</var> is <em>true</em>, attempt to decode the encoded
                {{BaseAudioContext/decodeAudioData(audioData, successCallback,
                errorCallback)/audioData!!argument}} into [=linear PCM=]. In case of
                failure, set <var>can decode</var> to <em>false</em>.

                If the media byte-stream contains multiple audio tracks, only decode the
                first track to [=linear pcm=].

                Note: Authors who need more control over the decoding process can use
                [[WEBCODECS]].

            4. If |can decode| is `false`,
                <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to execute the following steps:

                1. Let <var>error</var> be a <code>DOMException</code>
                    whose name is {{EncodingError}}.

                    2. Reject <var>promise</var> with <var>error</var>, and remove it from
                        {{BaseAudioContext/[[pending promises]]}}.

                3. If {{BaseAudioContext/decodeAudioData()/errorCallback!!argument}} is
                    not missing, invoke
                    {{BaseAudioContext/decodeAudioData()/errorCallback!!argument}} with
                    <var>error</var>.

            5. Otherwise:
                1. Take the result, representing the decoded [=linear PCM=]
                    audio data, and resample it to the sample-rate of the
                    {{BaseAudioContext}} if it is different from
                    the sample-rate of {{BaseAudioContext/decodeAudioData(audioData,
                    successCallback, errorCallback)/audioData!!argument}}.

                2. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                    queue a media element task</a> to execute the following steps:

                    1. Let <var>buffer</var> be an
                        {{AudioBuffer}} containing the final result
                        (after possibly performing sample-rate conversion).

                    2. Resolve <var>promise</var> with <var>buffer</var>.

                    3. If {{BaseAudioContext/decodeAudioData()/successCallback!!argument}}
                        is not missing, invoke
                        {{BaseAudioContext/decodeAudioData()/successCallback!!argument}}
                        with <var>buffer</var>.
        </div>

        <pre class=argumentdef for="BaseAudioContext/decodeAudioData()">
        audioData: An ArrayBuffer containing compressed audio data.
        successCallback: A callback function which will be invoked when the decoding is finished. The single argument to this callback is an AudioBuffer representing the decoded PCM audio data.
        errorCallback: A callback function which will be invoked if there is an error decoding the audio file.
        </pre>

        <div>
            <em>Return type:</em> {{Promise}}&lt;{{AudioBuffer}}&gt;
        </div>

</dl>

<h4 id="callback-decodesuccesscallback-parameters" callback lt="DecodeSuccessCallback()">
Callback {{DecodeSuccessCallback()}} Parameters</h4>

<dl dfn-type=argument dfn-for="DecodeSuccessCallback()">
    : {{DecodeSuccessCallback/decodedData!!argument}}, of type {{AudioBuffer}}
    :: The AudioBuffer containing the decoded audio data.
</dl>

<h4 id="callback-decodeerrorcallback-parameters" callback lt="DecodeErrorCallback()">
Callback {{DecodeErrorCallback()}} Parameters</h4>

<dl dfn-type=argument dfn-for="DecodeErrorCallback()">
    : {{DecodeErrorCallback/error!!argument}}, of type {{DOMException}}
    :: The error that occurred while decoding.
</dl>

<h4 id="lifetime-AudioContext" class="informative">
Lifetime</h4>

Once created, an {{AudioContext}} will continue to play
sound until it has no more sound to play, or the page goes away.

<h4 id="lack-of-introspection-or-serialization-primitives" class=informative>
Lack of Introspection or Serialization Primitives</h4>

The Web Audio API takes a <em>fire-and-forget</em> approach to
audio source scheduling. That is, <a>source nodes</a> are created
for each note during the lifetime of the {{AudioContext}}, and
never explicitly removed from the graph. This is incompatible with
a serialization API, since there is no stable set of nodes that
could be serialized.

Moreover, having an introspection API would allow content script to
be able to observe garbage collections.

<h4 id="system-resources-associated-with-baseaudiocontext-subclasses">
System Resources Associated with {{BaseAudioContext}} Subclasses</h4>

The subclasses {{AudioContext}} and {{OfflineAudioContext}}
should be considered expensive objects. Creating these objects may
involve creating a high-priority thread, or using a low-latency
system audio stream, both having an impact on energy consumption.
It is usually not necessary to create more than one
{{AudioContext}} in a document.

Constructing or resuming a {{BaseAudioContext}} subclass
involves <dfn id="acquiring">acquiring system resources</dfn> for
that context. For {{AudioContext}}, this also requires creation
of a system audio stream. These operations return when the context
begins generating output from its associated audio graph.

Additionally, a user-agent can have an implementation-defined
maximum number of {{AudioContext}}s, after which any attempt to
create a new {{AudioContext}} will fail, <span class="synchronous">throwing {{NotSupportedError}}</span>.

{{AudioContext/suspend}} and {{AudioContext/close}} allow authors to <dfn id="releasing">release system resources</dfn>, including threads,
processes and audio streams. Suspending a {{BaseAudioContext}}
permits implementations to release some of its resources, and
allows it to continue to operate later by invoking
{{AudioContext/resume}}. Closing an
{{AudioContext}} permits implementations to release all of its
resources, after which it cannot be used or resumed again.

Note: For example, this can involve waiting for the audio callbacks to
fire regularly, or to wait for the hardware to be ready for
processing.

<!--
   ███     ██████
  ██ ██   ██    ██
 ██   ██  ██
██     ██ ██
█████████ ██
██     ██ ██    ██
██     ██  ██████
-->

<h3 interface lt="AudioContext" id="AudioContext">
The {{AudioContext}} Interface</h3>

This interface represents an audio graph whose
{{AudioDestinationNode}} is routed to a real-time
output device that produces a signal directed at the user. In most
use cases, only a single {{AudioContext}} is used per
document.

<pre class="idl">
enum AudioContextLatencyCategory {
        "balanced",
        "interactive",
        "playback"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="AudioContextLatencyCategory">
    <caption>{{AudioContextLatencyCategory}} enumeration description</caption>
    <thead>
        <tr>
            <th>Enum value</th><th>Description</th>
    <tbody>
        <tr>
            <td>
                "<dfn>balanced</dfn>"
            <td>
                Balance audio output latency and power consumption.
        <tr>
            <td>
                "<dfn>interactive</dfn>"
            <td>
                Provide the lowest audio output latency possible without
                glitching. This is the default.
        <tr>
            <td>
                "<dfn>playback</dfn>"
            <td>
                Prioritize sustained playback without interruption over audio
                output latency. Lowest power consumption.
</table>
</div>

<pre class="idl">
enum AudioSinkType {
    "none"
};
</pre>

<div class="enum-description">
    <table class="simple" dfn-type=enum-value dfn-for="AudioSinkType">
        <caption>{{AudioSinkType}} Enumeration description</caption>
        <thead>
            <tr>
                <th>Enum Value</th><th>Description</th>
        <tbody>
            <tr>
                <td>
                    "<dfn>none</dfn>"
                <td>
                    The audio graph will be processed without being played
                    through an audio output device.
    </table>
</div>

<xmp class="idl">
[Exposed=Window]
interface AudioContext : BaseAudioContext {
    constructor (optional AudioContextOptions contextOptions = {});
    readonly attribute double baseLatency;
    readonly attribute double outputLatency;
    [SecureContext] readonly attribute (DOMString or AudioSinkInfo) sinkId;
    attribute EventHandler onsinkchange;
    attribute EventHandler onerror;
    AudioTimestamp getOutputTimestamp ();
    Promise<undefined> resume ();
    Promise<undefined> suspend ();
    Promise<undefined> close ();
    [SecureContext] Promise<undefined> setSinkId ((DOMString or AudioSinkOptions) sinkId);
    MediaElementAudioSourceNode createMediaElementSource (HTMLMediaElement mediaElement);
    MediaStreamAudioSourceNode createMediaStreamSource (MediaStream mediaStream);
    MediaStreamTrackAudioSourceNode createMediaStreamTrackSource (
        MediaStreamTrack mediaStreamTrack);
    MediaStreamAudioDestinationNode createMediaStreamDestination ();
};
</xmp>

An {{AudioContext}} is said to be <dfn>allowed to start</dfn> if the user agent
allows the context state to transition from "{{AudioContextState/suspended}}" to
"{{AudioContextState/running}}". A user agent may disallow this initial transition,
and to allow it only when the {{AudioContext}}'s [=relevant global object=] has
[=sticky activation=].

{{AudioContext}} has following internal slots:

<dl dfn-type=attribute dfn-for="AudioContext">
    : <dfn>[[suspended by user]]</dfn>
    ::
        A boolean flag representing whether the context is suspended by user code.
        The initial value is <code>false</code>.

    : <dfn>[[sink ID]]</dfn>
    ::
        A {{DOMString}} or an {{AudioSinkInfo}} representing the identifier
        or the information of the current audio output device respectively. The
        initial value is <code>""</code>, which means the default audio output
        device.

    : <dfn>[[sink ID at construction]]</dfn>
    ::
        A {{DOMString}} or an {{AudioSinkInfo}} representing the identifier
        or the information of the audio output device requested at construction,
        respectively. The initial value is <code>""</code>, which means the
        default audio output device.

    : <dfn>[[pending resume promises]]</dfn>
    :: 
        An ordered list to store pending {{Promise}}s created by
        {{AudioContext/resume()}}. It is initially empty.
</dl>

<h4 id="AudioContext-constructors">
Constructors</h4>

<dl dfn-type="constructor" dfn-for="AudioContext">
    : <dfn>AudioContext(contextOptions)</dfn>
    ::
        <div algorithm="AudioContext()">

        <p>
            If the [=current settings object=]'s [=relevant global object=]'s
            [=associated Document=] is NOT [=fully active=], throw an
            "{{InvalidStateError}}" and abort these steps.
        </p>
            <span class="synchronous">When creating an {{AudioContext}},
            execute these steps:</span>
            
            1. Let |context| be a new {{AudioContext}} object.

            1. Set a {{[[control thread state]]}} to <code>suspended</code> on
                |context|.

            1. Set a {{[[rendering thread state]]}} to <code>suspended</code> on
                |context|.
            
            1. Set {{[[state before interruption]]}} to `null` on |context|.

            1. Let |messageChannel| be a new {{MessageChannel}}.

            1. Let |controlSidePort| be the value of
                |messageChannel|'s {{MessageChannel/port1}} attribute.

            1. Let |renderingSidePort| be the value of
                |messageChannel|'s {{MessageChannel/port2}} attribute.

            1. Let |serializedRenderingSidePort| be the result of
                [$StructuredSerializeWithTransfer$](|renderingSidePort|,
                « |renderingSidePort| »).

            1. Set this {{BaseAudioContext/audioWorklet}}'s {{AudioWorklet/port}}
                to |controlSidePort|.

            1. <a>Queue a control message</a> to <a
                href="#setting-the-messageport-on-the-scope">set the
                MessagePort on the AudioContextGlobalScope</a>, with
                |serializedRenderingSidePort|.

            1. If <code>contextOptions</code> is given, perform the following
                substeps:

                1. If {{AudioContextOptions/sinkId}} is specified, let |sinkId| be
                    the value of
                    <code>contextOptions.{{AudioContextOptions/sinkId}}</code> and
                    run the following substeps:

                    1. If both |sinkId| and {{AudioContext/[[sink ID]]}} are a type of
                        {{DOMString}}, and they are equal to each other, abort these
                        substeps.

                    1. If |sinkId| is a type of {{AudioSinkOptions}} and
                        {{AudioContext/[[sink ID]]}} is a type of {{AudioSinkInfo}}, and
                        {{AudioSinkOptions/type}} in |sinkId| and {{AudioSinkInfo/type}}
                        in {{AudioContext/[[sink ID]]}} are equal, abort these substeps.

                    1. If |sinkId| is a type of {{DOMString}}, set
                        {{AudioContext/[[sink ID at construction]]}} to |sinkId| and abort these
                        substeps.

                    1. If |sinkId| is a type of {{AudioSinkOptions}}, set
                        {{AudioContext/[[sink ID at construction]]}} to a new instance of
                        {{AudioSinkInfo}} created with the value of
                        {{AudioSinkOptions/type}} of |sinkId|.

                1. Set the internal latency of |context| according to
                    <code>contextOptions.{{AudioContextOptions/latencyHint}}</code>,
                    as described in {{AudioContextOptions/latencyHint}}.

                1. If <code>contextOptions.{{AudioContextOptions/sampleRate}}
                    </code> is specified, set the {{BaseAudioContext/sampleRate}} of
                    |context| to this value. Otherwise, follow these substeps:

                    1. If |sinkId| is the empty string or a type of
                        {{AudioSinkOptions}}, use the sample rate of the default output
                        device. Abort these substeps.
                    
                    1. If |sinkId| is a {{DOMString}}, use the sample rate of the
                        output device identified by |sinkId|. Abort these substeps.
                    
                    If <code>contextOptions.{{AudioContextOptions/sampleRate}}</code>
                    differs from the sample rate of the output device, the user agent
                    MUST resample the audio output to match the sample rate of the
                    output device.

                    Note: If resampling is required, the latency of |context| may be
                    affected, possibly by a large amount.

            1. If |context| is <a>allowed to start</a>, send a
                <a>control message</a> to start processing.

            1. Return |context|.
        </div>

        <div algorithm="sending a control message to start processing">
        Sending a <a>control message</a> to start processing means
        executing the following steps:

        1. Let |validationResult| be the return value of
                <a href="#validating-sink-identifier">sink identifier validation
                </a> of {{AudioContext/[[sink ID at construction]]}}.

        1. If |validationResult| is <code>false</code>, execute the following steps:

                1. Set {{AudioContext/[[sink ID]]}} to the empty string.

                1. [=Queue a media element task=] to [=fire an event=]
                    named {{AudioContext/error}} at the {{AudioContext}},
                    and abort the following steps.

        1. Attempt to [=acquire system resources=] to use a following audio output device
            based on {{AudioContext/[[sink ID at construction]]}} for rendering:

            * The default audio output device for the empty string.
            * An audio output device identified by {{AudioContext/[[sink ID at construction]]}}.

                1. If resource acquisition fails, [=queue a media element
                    task=] to [=fire an event=] named
                    {{AudioContext/error}} at the {{AudioContext}}, and
                    abort the following steps.

        1. Set {{AudioContext/[[sink ID]]}} to the value of {{AudioContext/[[sink ID at construction]]}}.

        1. Set [=this=] {{[[rendering thread state]]}} to <code>running</code> on the
            {{AudioContext}}.

        1. [=Queue a media element task=] to execute the following steps:

            1. Set the {{BaseAudioContext/state}} attribute of the {{AudioContext}}
                to "{{AudioContextState/running}}".

            1. [=fire an event=] named {{BaseAudioContext/statechange}} at the
                {{AudioContext}}.
                
        </div>

        NOTE: In cases where an {{AudioContext}} is constructed with no arguments and resource
        acquisition fails, the User-Agent will attempt to silently render the audio graph using
        a mechanism that emulates an audio output device.

        <div algorithm="setting the messageport on the scope" id="setting-the-messageport-on-the-scope">
        Sending a <a>control message</a> to set the {{MessagePort}} on the
        {{AudioWorkletGlobalScope}} means executing the following steps, on
        the <a>rendering thread</a>, with
        |serializedRenderingSidePort|, that has been transfered to
        the {{AudioWorkletGlobalScope}}:

        1. Let |deserializedPort| be the result of
            [$StructuredDeserialize$](|serializedRenderingSidePort|,
            the current Realm).

        1. Set {{AudioWorkletGlobalScope/port}} to
            |deserializedPort|.
        
        </div>

    <pre class="argumentdef" for="AudioContext/constructor(contextOptions)">
    contextOptions: User-specified options controlling how the {{AudioContext}} should be constructed.
    </pre>

</dl>

<h4 id="AudioContext-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioContext">
    : <dfn>baseLatency</dfn>
    ::
        This represents the number of seconds of processing latency
        incurred by the {{AudioContext}} passing the audio from the
        {{AudioDestinationNode}} to the audio subsystem. It does not
        include any additional latency that might be caused by any
        other processing between the output of the
        {{AudioDestinationNode}} and the audio hardware and
        specifically does not include any latency incurred the audio
        graph itself.

        For example, if the audio context is running at 44.1 kHz with default render
        quantum size, and the {{AudioDestinationNode}} implements double buffering
        internally and can process and output audio each <a>render quantum</a>, then
        the processing latency is \((2\cdot128)/44100 = 5.805 \mathrm{ ms}\),
        approximately.

    : <dfn>outputLatency</dfn>
    ::
        The estimation in seconds of audio output latency, i.e., the
        interval between the time the UA requests the host system to
        play a buffer and the time at which the first sample in the
        buffer is actually processed by the audio output device. For
        devices such as speakers or headphones that produce an acoustic
        signal, this latter time refers to the time when a sample's
        sound is produced.

        An {{outputLatency}} attribute value depends on the platform and
        the connected audio output device hardware. The
        {{outputLatency}} attribute value may change while the context
        is running or the associated audio output device changes. It is
        useful to query this value frequently when accurate
        synchronization is required.

    : <dfn>sinkId</dfn>
    ::
        Returns the value of {{AudioContext/[[sink ID]]}} internal slot. This
        attribute is cached upon update, and it returns the same object after
        caching.

    : <dfn>onsinkchange</dfn>
    ::
        An [=event handler=] for {{AudioContext/setSinkId()}}. The event type of
        this event handler is <dfn event>sinkchange</dfn>. This event will be
        dispatched when changing the output device is completed.
        
        NOTE: This is not dispatched for the initial device selection in the
        construction of {{AudioContext}}. The {{BaseAudioContext/statechange}} event
        is available to check the readiness of the initial output device.

    : <dfn>onerror</dfn>
    ::
        An [=event handler=] for the {{Event}} dispatched from an {{AudioContext}}. The event
            type of this handler is <dfn event for=AudioContext>error</dfn> and the user agent can
            dispatch this event in the following cases:

            * When initializing and activating a selected audio device encounters failures.
            * When the audio output device associated with an {{AudioContext}} is disconnected while
                the context is {{AudioContextState/running}}.
            * When the operating system reports an audio device malfunction.

</dl>

<h4 id="AudioContext-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AudioContext">
    : <dfn>close()</dfn>
    ::
        Closes the {{AudioContext}}, [=release system resources|releasing the system
        resources=] being used. This will not automatically release
        all {{AudioContext}}-created objects, but will suspend the
        progression of the {{AudioContext}}'s
        {{BaseAudioContext/currentTime}}, and stop
        processing audio data.

        <div algorithm="AudioContext.close()">
            <span class="synchronous">When close is called, execute these steps:</span>

            1. If [=this=]'s [=relevant global object=]'s [=associated Document=] is not [=fully active=] then return [=a promise rejected with=] "{{InvalidStateError}}" {{DOMException}}.

            1. Let <var>promise</var> be a new Promise.

            1. If the {{[[control thread state]]}} flag on the
                {{AudioContext}} is <code>closed</code> reject the promise
                with {{InvalidStateError}}, abort these steps,
                returning <var>promise</var>.

            1. Set the {{[[control thread state]]}} flag on the {{AudioContext}} to
                <code>closed</code>.

            1. <a>Queue a control message</a> to close the {{AudioContext}}.

            1. Return <em>promise</em>.
        </div>

        <div algorithm="run a control message to close an AudioContext">
            Running a <a>control message</a> to close an
            {{AudioContext}} means running these steps on the
            <a>rendering thread</a>:

            1. Attempt to <a>release system resources</a>.

            2. Set the {{[[rendering thread state]]}} to <code>suspended</code>.
                <div class="note">
                    This will stop rendering.
                </div>

            3. If this <a>control message</a> is being run in a reaction to the
                document being unloaded, abort this algorithm.
                <div class="note">
                    There is no need to notify the control thread in this case.
                </div>

            4. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to execute the following steps:

                1. Resolve <em>promise</em>.
                2. If the {{BaseAudioContext/state}} attribute of the {{AudioContext}} is not already "{{AudioContextState/closed}}":
                    1. Set the {{BaseAudioContext/state}} attribute of the {{AudioContext}} to "{{AudioContextState/closed}}".

                    1. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                        queue a media element task</a> to <a spec="dom" lt="fire an event">fire
                        an event</a> named {{BaseAudioContext/statechange}} at the {{AudioContext}}.
        </div>

        When an {{AudioContext}} is closed, any
        {{MediaStream}}s and {{HTMLMediaElement}}s
        that were connected to an {{AudioContext}} will have their
        output ignored. That is, these will no longer cause any output
        to speakers or other output devices. For more flexibility in
        behavior, consider using <a href="https://www.w3.org/TR/mediacapture-fromelement/#dom-htmlmediaelement-capturestream">
        <code>HTMLMediaElement.captureStream()</code></a>.

        Note: When an {{AudioContext}} has been closed, implementation can
        choose to aggressively release more resources than when
        suspending.

        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{Promise}}&lt;{{undefined}}&gt;
        </div>

    : <dfn>createMediaElementSource(mediaElement)</dfn>
    ::
        Creates a {{MediaElementAudioSourceNode}}
        given an {{HTMLMediaElement}}. As a consequence of calling this
        method, audio playback from the {{HTMLMediaElement}} will be
        re-routed into the processing graph of the
        {{AudioContext}}.

        <pre class=argumentdef for="AudioContext/createMediaElementSource()">
        mediaElement: The media element that will be re-routed.
        </pre>

        <div>
            <em>Return type:</em> {{MediaElementAudioSourceNode}}
        </div>

    : <dfn>createMediaStreamDestination()</dfn>
    ::
        Creates a {{MediaStreamAudioDestinationNode}}

        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em>
            {{MediaStreamAudioDestinationNode}}
        </div>

    : <dfn>createMediaStreamSource(mediaStream)</dfn>
    ::
        Creates a {{MediaStreamAudioSourceNode}}.

        <pre class=argumentdef for="AudioContext/createMediaStreamSource()">
        mediaStream: The media stream that will act as source.
        </pre>

        <div>
            <em>Return type:</em> {{MediaStreamAudioSourceNode}}
        </div>

    : <dfn>createMediaStreamTrackSource(mediaStreamTrack)</dfn>
    ::
        Creates a {{MediaStreamTrackAudioSourceNode}}.

        <pre class=argumentdef for="AudioContext/createMediaStreamTrackSource()">
        mediaStreamTrack: The {{MediaStreamTrack}} that will act as source. <span class="synchronous">The value of its <code>kind</code> attribute must be equal to <code>"audio"</code>, or an {{InvalidStateError}} exception MUST be thrown.</span>
        </pre>

        <div>
            <em>Return type:</em>
            {{MediaStreamTrackAudioSourceNode}}
        </div>

    : <dfn>getOutputTimestamp()</dfn>
    ::
        Returns a new {{AudioTimestamp}} instance
        containing two related audio stream position
        values for the context: the {{AudioTimestamp/contextTime}} member contains
        the time of the sample frame which is currently being rendered
        by the audio output device (i.e., output audio stream
        position), in the same units and origin as context's
        {{BaseAudioContext/currentTime}}; the
        {{AudioTimestamp/performanceTime}} member
        contains the time estimating the moment when the sample frame
        corresponding to the stored <code>contextTime</code> value was
        rendered by the audio output device, in the same units and
        origin as <code>performance.now()</code> (described in
        [[!hr-time-3]]).

        If the context's rendering graph has not yet processed a block
        of audio, then {{getOutputTimestamp}} call
        returns an {{AudioTimestamp}} instance with both
        members containing zero.

        After the context's rendering graph has started processing of
        blocks of audio, its {{BaseAudioContext/currentTime}} attribute value
        always exceeds the {{AudioTimestamp/contextTime}} value obtained
        from {{AudioContext/getOutputTimestamp}} method call.

        <div class=example>
            The value returned from {{getOutputTimestamp}}
            method can be used to get performance time estimation for the
            slightly later context's time value:

            <pre highlight="js">
                function outputPerformanceTime(contextTime) {
                    const timestamp = context.getOutputTimestamp();
                    const elapsedTime = contextTime - timestamp.contextTime;
                    return timestamp.performanceTime + elapsedTime * 1000;
                }
            </pre>

            In the above example the accuracy of the estimation depends on
            how close the argument value is to the current output audio
            stream position: the closer the given <code>contextTime</code>
            is to <code>timestamp.contextTime</code>, the better the
            accuracy of the obtained estimation.
        </div>

        Note: The difference between the values of the context's
        {{BaseAudioContext/currentTime}} and the
        {{AudioTimestamp/contextTime}}
        obtained from {{AudioContext/getOutputTimestamp}} method call
        cannot be considered as a reliable output latency estimation
        because {{BaseAudioContext/currentTime}} may be
        incremented at non-uniform time intervals, so {{AudioContext/outputLatency}} attribute should
        be used instead.

        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{AudioTimestamp}}
        </div>

    : <dfn>resume()</dfn>
    ::
        Resumes the progression of the {{AudioContext}}'s
        {{BaseAudioContext/currentTime}} when it has
        been suspended.

        <div algorithm="AudioContext::resume()">
            <span class="synchronous">When resume is called,
            execute these steps:</span>

            1. If [=this=]'s [=relevant global object=]'s
                [=associated Document=] is not [=fully active=] then return
                [=a promise rejected with=] "{{InvalidStateError}}"
                {{DOMException}}.

            1. Let <var>promise</var> be a new Promise.

            1. If the {{[[control thread state]]}} on the
                {{AudioContext}} is <code>closed</code> reject the
                promise with {{InvalidStateError}}, abort these steps,
                returning <var>promise</var>.

            1. Set {{[[suspended by user]]}} to <code>false</code>.
            
            1. If the context's {{BaseAudioContext/state}} attribute is 
                "{{AudioContextState/suspended}}" and the context's
                {{[[control thread state]]}} is 
                "{{AudioContextState/interrupted}}", then:

                1. <a>Queue a media element task</a> to execute the following steps:

                    1. Set the {{BaseAudioContext/state}} attribute of the
                        {{AudioContext}} to "{{AudioContextState/interrupted}}".
                    
                    1. Set the {{[[state before interruption]]}} slot to
                        "{{AudioContextState/running}}".

                    1. [=Queue a media element task=] to [=fire an event=] named
                        {{BaseAudioContext/statechange}} at the {{AudioContext}}.
                
                1. Reject the promise with {{InvalidStateError}}, abort these
                    steps, returning <var>promise</var>.

            1. If the context is not <a>allowed to start</a>, append
                <var>promise</var> to {{BaseAudioContext/[[pending promises]]}}
                and {{AudioContext/[[pending resume promises]]}} and abort
                these steps, returning <var>promise</var>.

            1. Set the {{[[control thread state]]}} on the {{AudioContext}} to
                <code>running</code>.

            1. <a>Queue a control message</a> to resume the {{AudioContext}} with <var>promise</var>.

            1. Return <var>promise</var>.
        </div>

        <div id="context-resume" algorithm="run a control message in AudioContext">
            Running a <a>control message</a> to resume an
            {{AudioContext}} means running these steps on the
            <a>rendering thread</a>:

            1. Let <var>promise</var> be the promise passed into this algorithm.

            1. Attempt to <a href="#acquiring">acquire system resources</a>.

            2. Set the {{[[rendering thread state]]}} on the {{AudioContext}} to <code>running</code>.

            3. Start <a href="#rendering-loop">rendering the audio graph</a>.

            4. In case of failure,
                <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to execute the following steps:

                1. Reject all promises from {{AudioContext/[[pending resume promises]]}}
                    in order, then clear {{AudioContext/[[pending resume promises]]}}.

                2. Additionally, remove those promises from {{BaseAudioContext/[[pending
                    promises]]}}.

            5. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to execute the following steps:

                1. Resolve all promises from {{AudioContext/[[pending resume promises]]}} in order.
                1. Clear {{AudioContext/[[pending resume promises]]}}. Additionally, remove those
                    promises from {{BaseAudioContext/[[pending promises]]}}.

                2. Resolve <var>promise</var>.

                3. If the {{BaseAudioContext/state}} attribute of the {{AudioContext}} is not already "{{AudioContextState/running}}":

                    1. Set the {{BaseAudioContext/state}} attribute of the {{AudioContext}} to "{{AudioContextState/running}}".

                    1. [=Queue a media element task=] to [=fire an event=] named
                        {{BaseAudioContext/statechange}} at the {{AudioContext}}.
        </div>

        <div>
            <em>No parameters.</em>
        </div>

        <div>
            <em>Return type:</em> {{Promise}}&lt;{{undefined}}&gt;
        </div>

    : <dfn>suspend()</dfn>
    ::
        Suspends the progression of {{AudioContext}}'s
        {{BaseAudioContext/currentTime}}, allows any
        current context processing blocks that are already processed to
        be played to the destination, and then allows the system to
        release its claim on audio hardware. This is generally useful
        when the application knows it will not need the
        {{AudioContext}} for some time, and wishes to temporarily
        <a>release system resource</a> associated with the
        {{AudioContext}}. The promise resolves when the frame buffer
        is empty (has been handed off to the hardware), or immediately
        (with no other effect) if the context is already
        <code>suspended</code>. The promise is rejected if the context
        has been closed.

        <div algorithm="AudioContext.suspend()">
            <span class="synchronous">When suspend is called, execute these steps:</span>

            1. If [=this=]'s [=relevant global object=]'s [=associated Document=] is not [=fully active=] then return [=a promise rejected with=] "{{InvalidStateError}}" {{DOMException}}.

            1. Let <var>promise</var> be a new Promise.

            2. If the {{[[control thread state]]}} on the
                {{AudioContext}} is <code>closed</code> reject the promise
                with {{InvalidStateError}}, abort these steps,
                returning <var>promise</var>.

            3. Append <var>promise</var> to {{BaseAudioContext/[[pending promises]]}}.

            4. Set {{[[suspended by user]]}} to <code>true</code>.

            5. Set the {{[[control thread state]]}} on the {{AudioContext}} to <code>suspended</code>.

            6. <a>Queue a control message</a> to suspend the {{AudioContext}} with <var>promise</var>.

            7. Return <var>promise</var>.
        </div>

        <div algorithm="run a control message to suspend an AudioContext">
            Running a <a>control message</a> to suspend an
            {{AudioContext}} means running these steps on the
            <a>rendering thread</a>:

            1. Let <var>promise</var> be the promise passed into this algorithm.

            1. Attempt to <a>release system resources</a>.

            1. If the {{[[rendering thread state]]}} on the {{AudioContext}} is
                "{{AudioContextState/interrupted}}", <a>queue a media element
                task</a> to set the {{[[state before interruption]]}} slot to
                "{{AudioContextState/suspended}}".

            1. Set the {{[[rendering thread state]]}} on the {{AudioContext}} to
                "{{AudioContextState/suspended}}".

            1. <a>Queue a media element task</a> to execute the following steps:

                1. Resolve <var>promise</var>.

                1. If the {{BaseAudioContext/state}}
                    attribute of the {{AudioContext}} is not already "{{AudioContextState/suspended}}":

                    1. Set the {{BaseAudioContext/state}} attribute of the {{AudioContext}} to "{{AudioContextState/suspended}}".

                    1. [=Queue a media element task=] to [=fire an event=] named
                        {{BaseAudioContext/statechange}} at the {{AudioContext}}.
        </div>

        While an {{AudioContext}} is suspended,
        {{MediaStream}}s will have their output ignored; that
        is, data will be lost by the real time nature of media streams.
        {{HTMLMediaElement}}s will similarly have their output
        ignored until the system is resumed. {{AudioWorkletNode}}s
        and {{ScriptProcessorNode}}s will cease to have their
        processing handlers invoked while suspended, but will resume
        when the context is resumed. For the purpose of
        {{AnalyserNode}} window functions, the data is considered as
        a continuous stream - i.e. the
        <code>resume()</code>/<code>suspend()</code> does not cause
        silence to appear in the {{AnalyserNode}}'s stream of data.
        In particular, calling {{AnalyserNode}} functions repeatedly
        when a {{AudioContext}} is suspended MUST return the same
        data.

        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{Promise}}&lt;{{undefined}}&gt;
        </div>

    : <dfn>setSinkId((DOMString or AudioSinkOptions) sinkId)</dfn>
    ::
        Sets the identifier of an output device. When this method is invoked, the
        user agent MUST run the following steps:

        <div algorithm="AudioContext.setSinkId()">
            1. Let |sinkId| be the method's first argument.

            1. If |sinkId| is equal to {{AudioContext/[[sink ID]]}}, return a
                promise, resolve it immediately and abort these steps.

            1. Let |validationResult| be the return value of
                <a href="#validating-sink-identifier">sink identifier validation</a>
                of |sinkId|.

            1. If |validationResult| is <code>false</code>, return a promise
                rejected with a new {{DOMException}} whose name is
                "{{NotAllowedError}}". Abort these steps.

            1. Let |p| be a new promise.

            1. Send a <a>control message</a> with |p| and |sinkId| to start
                processing.

            1. Return |p|.
        </div>

        <div algorithm="run a control message for setSinkId">
            Sending a <a>control message</a> to start processing during
            {{AudioContext/setSinkId()}} means executing the following steps:

            1. Let |p| be the promise passed into this algorithm.

            1. Let |sinkId| be the sink identifier passed into this algorithm.

            1. If both |sinkId| and {{AudioContext/[[sink ID]]}} are a type of
                {{DOMString}}, and they are equal to each other,
                <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to resolve |p| and abort these steps.

            1. If |sinkId| is a type of {{AudioSinkOptions}} and
                {{AudioContext/[[sink ID]]}} is a type of {{AudioSinkInfo}}, and
                {{AudioSinkOptions/type}} in |sinkId| and {{AudioSinkInfo/type}} in
                {{AudioContext/[[sink ID]]}} are equal,
                <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to resolve |p| and abort these steps.

            1. Let |wasRunning| be true.

            1. Set |wasRunning| to false if the {{[[rendering thread state]]}} on
                the {{AudioContext}} is <code>"suspended"</code>.

            1. Pause the renderer after processing the current render quantum.

            1. Attempt to <a>release system resources</a>.

            1. If |wasRunning| is true:

                1. Set the {{[[rendering thread state]]}} on the {{AudioContext}} to
                    <code>"suspended"</code>.
            
                1. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                    Queue a media element task</a> to execute the following steps:

                    1. If the {{BaseAudioContext/state}} attribute of the
                        {{AudioContext}} is not already "{{AudioContextState/suspended}}":

                        1. Set the {{BaseAudioContext/state}} attribute of the
                            {{AudioContext}} to "{{AudioContextState/suspended}}".

                        1. [=Fire an event=] named {{BaseAudioContext/statechange}} at the
                            associated {{AudioContext}}.

            1. Attempt to <a href="#acquiring">acquire system resources</a> to use
                a following audio output device based on {{AudioContext/[[sink ID]]}}
                for rendering:

                * The default audio output device for the empty string.
                * A audio output device identified by {{AudioContext/[[sink ID]]}}.
            
                In case of failure, reject |p| with "{{InvalidAccessError}}" abort
                the following steps.
            
            1. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                Queue a media element task</a> to execute the following steps:

                1. If |sinkId| is a type of {{DOMString}}, set
                    {{AudioContext/[[sink ID]]}} to |sinkId|. Abort these steps.

                1. If |sinkId| is a type of {{AudioSinkOptions}} and
                    {{AudioContext/[[sink ID]]}} is a type of {{DOMString}},
                    set {{AudioContext/[[sink ID]]}} to a new instance of
                    {{AudioSinkInfo}} created with the value of
                    {{AudioSinkOptions/type}} of |sinkId|.

                1. If |sinkId| is a type of {{AudioSinkOptions}} and
                    {{AudioContext/[[sink ID]]}} is a type of {{AudioSinkInfo}},
                    set {{AudioSinkInfo/type}} of {{AudioContext/[[sink ID]]}} to
                    the {{AudioSinkOptions/type}} value of |sinkId|.

                1. Resolve |p|.
                
                1. [=Fire an event=] named {{AudioContext/sinkchange}} at the
                    associated {{AudioContext}}.

            1. If |wasRunning| is true:

                1. Set the {{[[rendering thread state]]}} on the {{AudioContext}} to
                    <code>"running"</code>.

                1. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                    Queue a media element task</a> to execute the following steps:

                    1. If the {{BaseAudioContext/state}} attribute of the
                        {{AudioContext}} is not already "{{AudioContextState/running}}":

                        1. Set the {{BaseAudioContext/state}} attribute of the
                            {{AudioContext}} to "{{AudioContextState/running}}".
                        
                        1. [=Fire an event=] named {{BaseAudioContext/statechange}} at the
                            associated {{AudioContext}}.
        </div>
</dl>

<h4 id="validating-sink-identifier">
Validating {{AudioContext/sinkId}}</h4>

This algorithm is used to validate the information provided to modify
{{AudioContext/sinkId}}:

<div algorithm="validating sink ID">
    1. Let |document| be the current settings object's [=associated Document=].

    1. Let |sinkIdArg| be the value passed in to this algorithm.

    1. If |document| is not allowed to use the feature identified by
        <code>"speaker-selection"</code>, return <code>false</code>.

    1. If |sinkIdArg| is a type of {{DOMString}} but it is not equal to the empty
        string or it does not match any audio output device identified by the
        result that would be provided by {{MediaDevices/enumerateDevices()}},
        return <code>false</code>.

    1. Return <code>true</code>.
</div>

<h4 dictionary id="AudioContextOptions">
{{AudioContextOptions}}</h4>

The {{AudioContextOptions}} dictionary is used to
specify user-specified options for an {{AudioContext}}.

<pre class="idl">
    dictionary AudioContextOptions {
        (AudioContextLatencyCategory or double) latencyHint = "interactive";
        float sampleRate;
        (DOMString or AudioSinkOptions) sinkId;
        (AudioContextRenderSizeCategory or unsigned long) renderSizeHint = "default";
    };
</pre>

<h5 id="dictionary-audiocontextoptions-members">
Dictionary {{AudioContextOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="AudioContextOptions">
    : <dfn>latencyHint</dfn>
    ::
        Identify the type of playback, which affects tradeoffs
        between audio output latency and power consumption.

        The preferred value of the <code>latencyHint</code> is a
        value from {{AudioContextLatencyCategory}}. However, a
        double can also be specified for the number of seconds of
        latency for finer control to balance latency and power
        consumption. It is at the browser's discretion to interpret
        the number appropriately. The actual latency used is given by
        AudioContext's {{AudioContext/baseLatency}} attribute.

    : <dfn>sampleRate</dfn>
    ::
        Set the {{BaseAudioContext/sampleRate}} to this value
        for the {{AudioContext}} that will be created. The
        supported values are the same as the sample rates for an
        {{AudioBuffer}}. <span class="synchronous">A
        {{NotSupportedError}} exception MUST be thrown if
        the specified sample rate is not supported.</span>

        If {{AudioContextOptions/sampleRate}} is not
        specified, the preferred sample rate of the output device for
        this {{AudioContext}} is used.

    : <dfn>sinkId</dfn>
    ::
        The identifier or associated information of the audio output device.
        See {{AudioContext/sinkId}} for more details.

    : <dfn>renderSizeHint</dfn>
    ::
        This allows users to ask for a particular <a>render quantum size</a> when an
        integer is passed, to use the default of 128 frames if nothing or
        <code>"default"</code> is passed, or to ask the User-Agent to pick a good
        <a>render quantum size</a> if <code>"hardware"</code> is specified.

        It is a hint that might not be honored.
</dl>

<h4 dictionary id="AudioSinkOptions">
{{AudioSinkOptions}}</h4>

The {{AudioSinkOptions}} dictionary is used to specify options for
{{AudioContext/sinkId}}.

<pre class="idl">
dictionary AudioSinkOptions {
    required AudioSinkType type;
};
</pre>

<h5 id="dictionary-audiosinkoptions-members">
Dictionary {{AudioSinkOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="AudioSinkOptions">
    : <dfn>type</dfn>
    ::
        A value of {{AudioSinkType}} to specify the type of the device.
</dl>

<h4 interface id="AudioSinkInfo">
{{AudioSinkInfo}}</h4>

The {{AudioSinkInfo}} interface is used to get information on the current
audio output device via {{AudioContext/sinkId}}.

<pre class="idl">
[Exposed=Window]
interface AudioSinkInfo {
    readonly attribute AudioSinkType type;
};
</pre>

<h5 id="audiosinkinfo-attributes">
Attributes</h5>

<dl dfn-type=attribute dfn-for="AudioSinkInfo">
    : <dfn>type</dfn>
    ::
        A value of {{AudioSinkType}} that represents the type of the device.
</dl>

<h4 dictionary id="AudioTimestamp">
{{AudioTimestamp}}</h4>

<pre class="idl">
dictionary AudioTimestamp {
    double contextTime;
    DOMHighResTimeStamp performanceTime;
};
</pre>

<h5 id="dictionary-audiotimestamp-members">
Dictionary {{AudioTimestamp}} Members</h5>

<dl dfn-type=dict-member dfn-for="AudioTimestamp">
    : <dfn>contextTime</dfn>
    ::
        Represents a point in the time coordinate system of
        BaseAudioContext's {{BaseAudioContext/currentTime}}.

    : <dfn>performanceTime</dfn>
    ::
        Represents a point in the time coordinate system of a
        <code>Performance</code> interface implementation (described in
        [[!hr-time-3]]).
</dl>

<!--
 ███████  ████████ ████████ ██       ████ ██    ██ ████████          ███     ██████
██     ██ ██       ██       ██        ██  ███   ██ ██               ██ ██   ██    ██
██     ██ ██       ██       ██        ██  ████  ██ ██              ██   ██  ██
██     ██ ██████   ██████   ██        ██  ██ ██ ██ ██████         ██     ██ ██
██     ██ ██       ██       ██        ██  ██  ████ ██             █████████ ██
██     ██ ██       ██       ██        ██  ██   ███ ██             ██     ██ ██    ██
 ███████  ██       ██       ████████ ████ ██    ██ ████████       ██     ██  ██████
-->

<h3 interface lt="OfflineAudioContext" id="OfflineAudioContext">
The {{OfflineAudioContext}} Interface</h3>

{{OfflineAudioContext}} is a particular type of
{{BaseAudioContext}} for rendering/mixing-down
(potentially) faster than real-time. It does not render to the audio
hardware, but instead renders as quickly as possible, fulfilling the
returned promise with the rendered result as an
{{AudioBuffer}}.

<xmp class="idl">
[Exposed=Window]
interface OfflineAudioContext : BaseAudioContext {
    constructor(OfflineAudioContextOptions contextOptions);
    constructor(unsigned long numberOfChannels, unsigned long length, float sampleRate);
    Promise<AudioBuffer> startRendering();
    Promise<undefined> resume();
    Promise<undefined> suspend(double suspendTime);
    readonly attribute unsigned long length;
    attribute EventHandler oncomplete;
};
</xmp>

<h4 id="OfflineAudioContext-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="OfflineAudioContext">
    : <dfn>OfflineAudioContext(contextOptions)</dfn>
    ::
        <div algorithm="OfflineAudioContext.OfflineAudioContext(contextOptions)">

            <p>
                If the [=current settings object=]'s [=relevant global object=]'s
                [=associated Document=] is NOT [=fully active=],
                throw an {{InvalidStateError}} and abort these steps.
            </p>
            Let |c| be a new {{OfflineAudioContext}} object.
            Initialize |c| as follows:

            1. Set the {{[[control thread state]]}} for |c|
                to <code>"suspended"</code>.

            1. Set the {{[[rendering thread state]]}} for
                |c| to <code>"suspended"</code>.

            1. Determine the {{[[render quantum size]]}} for this {{OfflineAudioContext}},
                    based on the value of the {{OfflineAudioContextOptions/renderSizeHint}}:

                1. If it has the default value of <code>"default"</code> or
                        <code>"hardware</code>", set the {{[[render quantum size]]}} private
                        slot to 128.

                1. Else, if an integer has been passed, the User-Agent can decide to
                        honour this value by setting it to the {{[[render quantum size]]}}
                        private slot.

            1. Construct an {{AudioDestinationNode}} with its
                {{AudioNode/channelCount}} set to
                <code>contextOptions.numberOfChannels</code>.

            1. Let |messageChannel| be a new {{MessageChannel}}.

            1. Let |controlSidePort| be the value of
                |messageChannel|'s {{MessageChannel/port1}} attribute.

            1. Let |renderingSidePort| be the value of
                |messageChannel|'s {{MessageChannel/port2}} attribute.

            1. Let |serializedRenderingSidePort| be the result of
                [$StructuredSerializeWithTransfer$](|renderingSidePort|,
                « |renderingSidePort| »).

            1. Set this {{BaseAudioContext/audioWorklet}}'s {{AudioWorklet/port}} to
                |controlSidePort|.

            1. <a>Queue a control message</a> to <a
                href="#setting-the-messageport-on-the-scope">set the
                MessagePort on the AudioContextGlobalScope</a>, with
                |serializedRenderingSidePort|.
        </div>

        <pre class=argumentdef for="OfflineAudioContext/constructor(contextOptions)">
        contextOptions: The initial parameters needed to construct this context.
        </pre>

    : <dfn>OfflineAudioContext(numberOfChannels, length, sampleRate)</dfn>
    ::
        The {{OfflineAudioContext}} can be constructed with the same arguments
        as AudioContext.createBuffer. <span class="synchronous">A
        {{NotSupportedError}} exception MUST be thrown if any
        of the arguments is negative, zero, or outside its nominal
        range.</span>

        The OfflineAudioContext is constructed as if

        <pre highlight="js">
            new OfflineAudioContext({
                    numberOfChannels: numberOfChannels,
                    length: length,
                    sampleRate: sampleRate
            })
        </pre>

        were called instead.

        <pre class=argumentdef for="OfflineAudioContext/constructor(numberOfChannels, length, sampleRate)">
        numberOfChannels: Determines how many channels the buffer will have. See {{BaseAudioContext/createBuffer()}} for the supported number of channels.
        length: Determines the size of the buffer in sample-frames.
        sampleRate: Describes the sample-rate of the [=linear PCM=] audio data in the buffer in sample-frames per second. See {{BaseAudioContext/createBuffer()}} for valid sample rates.
        </pre>
</dl>

<h4 id="OfflineAudioContext-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="OfflineAudioContext">
    : <dfn>length</dfn>
    ::
        The size of the buffer in sample-frames. This is the same as the
        value of the <code>length</code> parameter for the constructor.

    : <dfn>oncomplete</dfn>
    ::
        The event type of this event handler is <dfn event>complete</dfn>. The event
        dispatched to the event handler will use the {{OfflineAudioCompletionEvent}}
        interface. It is the last event fired on an {{OfflineAudioContext}}.
</dl>

<h4 id="OfflineAudioContext-methods">
Methods</h4>

<dl dfn-type=method dfn-for="OfflineAudioContext">
    : <dfn>startRendering()</dfn>
    ::
        Given the current connections and scheduled changes, starts
        rendering audio.

        Although the primary method of getting the rendered audio data
        is via its promise return value, the instance will also fire an
        event named <code>complete</code> for legacy reasons.

        <div algorithm="OfflineAudioContext.startRendering()">
            Let <dfn attribute for="OfflineAudioContext">[[rendering started]]</dfn> be an internal slot of this {{OfflineAudioContext}}.  Initialize this slot to <em>false</em>.

            <span class="synchronous">When <code>startRendering</code> is
            called, the following steps MUST be performed on the <a>control
            thread</a>:</span>

            <ol>
                <li>If [=this=]'s [=relevant global object=]'s [=associated Document=] is not [=fully active=] then return [=a promise rejected with=] "{{InvalidStateError}}" {{DOMException}}.

                <li>If the {{[[rendering started]]}} slot on the
                {{OfflineAudioContext}} is <em>true</em>, return a rejected
                promise with {{InvalidStateError}}, and abort these
                steps.

                <li>Set the {{[[rendering started]]}} slot of the
                {{OfflineAudioContext}} to <em>true</em>.

                <li>Let <var>promise</var> be a new promise.

                <li>Create a new {{AudioBuffer}}, with a number of
                channels, length and sample rate equal respectively to the
                <code>numberOfChannels</code>, <code>length</code> and
                <code>sampleRate</code> values passed to this instance's
                constructor in the <code>contextOptions</code> parameter.
                Assign this buffer to an internal slot
                <dfn attribute for="OfflineAudioContext">[[rendered buffer]]</dfn> in the {{OfflineAudioContext}}.

                <li>If an exception was thrown during the preceding
                {{AudioBuffer}} constructor call, reject
                <var>promise</var> with this exception.

                <li>Otherwise, in the case that the buffer was successfully
                constructed, <a>begin offline rendering</a>.

                <li>Append <var>promise</var> to {{BaseAudioContext/[[pending promises]]}}.

                <li>Return <var>promise</var>.
            </ol>
        </div>

        <div algorithm="begin offline rendering">
            To <dfn dfn for>begin offline rendering</dfn>, the following steps MUST
            happen on a <a>rendering thread</a> that is created for the
            occasion.

            <ol>
                <li>Given the current connections and scheduled changes, start
                rendering <code>length</code> sample-frames of audio into
                {{[[rendered buffer]]}}

                <li>For every <a>render quantum</a>, check and
                {{OfflineAudioContext/suspend()|suspend}}
                rendering if necessary.

                <li>If a suspended context is resumed, continue to render the
                buffer.

                <li>Once the rendering is complete,
                    <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                    queue a media element task</a> to execute the following steps:

                    <ol>
                        <li>Resolve the <var ignore>promise</var> created by {{startRendering()}}
                        with {{[[rendered buffer]]}}.

                        <li>[=Queue a media element task=] to [=fire an event=] named
                        {{OfflineAudioContext/complete}} at the {{OfflineAudioContext}} using
                        {{OfflineAudioCompletionEvent}} whose `renderedBuffer` property is set to
                        {{[[rendered buffer]]}}.

                    </ol>

            </ol>
        </div>

        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{Promise}}&lt;{{AudioBuffer}}&gt;
        </div>

    : <dfn>resume()</dfn>
    ::
        Resumes the progression of the {{OfflineAudioContext}}'s
        {{BaseAudioContext/currentTime}} when it has
        been suspended.

        <div algorithm="OfflineAudioContext::resume()">
            <span class="synchronous">When resume is called,
            execute these steps:</span>

            1. If [=this=]'s [=relevant global object=]'s [=associated Document=] is
                not [=fully active=] then return [=a promise rejected with=]
                "{{InvalidStateError}}" {{DOMException}}.

            1. Let <var>promise</var> be a new Promise.

            1. Abort these steps and reject <var>promise</var> with
                {{InvalidStateError}} when any of following conditions is true:
                - The {{[[control thread state]]}} on the {{OfflineAudioContext}}
                    is <code>closed</code>.
                - The {{[[rendering started]]}} slot on the {{OfflineAudioContext}}
                    is <em>false</em>.

            1. Set the {{[[control thread state]]}} flag on the
                {{OfflineAudioContext}} to <code>running</code>.

            1. <a>Queue a control message</a> to resume the {{OfflineAudioContext}}.

            1. Return <var>promise</var>.
        </div>

        <div algorithm="run a control message in OfflineAudioContext">
            Running a <a>control message</a> to resume an
            {{OfflineAudioContext}} means running these steps on the
            <a>rendering thread</a>:

            1. Set the {{[[rendering thread state]]}} on the {{OfflineAudioContext}} to <code>running</code>.

            2. Start <a href="#rendering-loop">rendering the audio graph</a>.

            3. In case of failure,
                <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to reject |promise| and abort the remaining steps.

            4. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to execute the following steps:

                1. Resolve <var>promise</var>.

                2. If the {{BaseAudioContext/state}} attribute of the
                    {{OfflineAudioContext}} is not already "{{AudioContextState/running}}":

                    1. Set the {{BaseAudioContext/state}} attribute of the
                        {{OfflineAudioContext}} to "{{AudioContextState/running}}".

                    1. [=Queue a media element task=] to [=fire an event=] named
                        {{BaseAudioContext/statechange}} at the {{OfflineAudioContext}}.

        </div>

        <div>
            <em>No parameters.</em>
        </div>

        <div>
            <em>Return type:</em> {{Promise}}&lt;{{undefined}}&gt;
        </div>

    : <dfn>suspend(suspendTime)</dfn>
    ::
        Schedules a suspension of the time progression in the audio
        context at the specified time and returns a promise. This is
        generally useful when manipulating the audio graph
        synchronously on {{OfflineAudioContext}}.

        Note that the maximum precision of suspension is the size of
        the <a>render quantum</a> and the specified suspension time
        will be rounded up to the nearest <a>render quantum</a>
        boundary. For this reason, it is not allowed to schedule
        multiple suspends at the same quantized frame. Also, scheduling
        should be done while the context is not running to ensure
        precise suspension.

        <pre class=argumentdef for="OfflineAudioContext/suspend()">
        suspendTime: Schedules a suspension of the rendering at the specified time, which is quantized and rounded up to the <a>render quantum</a> size. If the quantized frame number <ol> <li>is negative or <li>is less than or equal to the current time or <li>is greater than or equal to the total render duration or <li>is scheduled by another suspend for the same time, </ol>then the promise is rejected with {{InvalidStateError}}.
        </pre>

        <div>
            <em>Return type:</em> {{Promise}}&lt;{{undefined}}&gt;
        </div>
</dl>

<h4 dictionary id="OfflineAudioContextOptions">
{{OfflineAudioContextOptions}}</h4>

This specifies the options to use in constructing an
{{OfflineAudioContext}}.

<pre class="idl">
dictionary OfflineAudioContextOptions {
    unsigned long numberOfChannels = 1;
    required unsigned long length;
    required float sampleRate;
    (AudioContextRenderSizeCategory or unsigned long) renderSizeHint = "default";
};
</pre>

<h5 id="dictionary-offlineaudiocontextoptions-members">
Dictionary {{OfflineAudioContextOptions}} Members</h5>

<dl dfn-type="dict-member" dfn-for="OfflineAudioContextOptions">
    : <dfn>length</dfn>
    ::
        The length of the rendered {{AudioBuffer}} in sample-frames.

    : <dfn>numberOfChannels</dfn>
    ::
        The number of channels for this {{OfflineAudioContext}}.

    : <dfn>sampleRate</dfn>
    ::
        The sample rate for this {{OfflineAudioContext}}.

    : <dfn>renderSizeHint</dfn>
    ::
        A hint for the <a>render quantum size</a> of this
        {{OfflineAudioContext}}.
</dl>

<h4 interface lt="OfflineAudioCompletionEvent" id="OfflineAudioCompletionEvent">
The {{OfflineAudioCompletionEvent}} Interface</h4>

This is an {{Event}} object which is dispatched to
{{OfflineAudioContext}} for legacy reasons.

<pre class="idl">
[Exposed=Window]
interface OfflineAudioCompletionEvent : Event {
    constructor (DOMString type, OfflineAudioCompletionEventInit eventInitDict);
    readonly attribute AudioBuffer renderedBuffer;
};
</pre>

<h5 id="OfflineAudioCompletionEvent-attributes">
Attributes</h5>

<dl dfn-type=attribute dfn-for="OfflineAudioCompletionEvent">
    : <dfn>renderedBuffer</dfn>
    ::
        An {{AudioBuffer}} containing the rendered audio data.
</dl>

<h5 dictionary id="OfflineAudioCompletionEventInit">
{{OfflineAudioCompletionEventInit}}</h5>

<pre class="idl">
dictionary OfflineAudioCompletionEventInit : EventInit {
    required AudioBuffer renderedBuffer;
};
</pre>

<h6 id="dictionary-offlineaudiocompletioneventinit-members">
Dictionary {{OfflineAudioCompletionEventInit}} Members</h6>

<dl dfn-type=dict-member dfn-for="OfflineAudioCompletionEventInit">
    : <dfn>renderedBuffer</dfn>
    ::
        Value to be assigned to the {{OfflineAudioCompletionEvent/renderedBuffer}} attribute of the event.
</dl>

<!--
   ███    ██     ██ ████████  ████  ███████  ████████  ██     ██ ████████ ████████ ████████ ████████
  ██ ██   ██     ██ ██     ██  ██  ██     ██ ██     ██ ██     ██ ██       ██       ██       ██     ██
 ██   ██  ██     ██ ██     ██  ██  ██     ██ ██     ██ ██     ██ ██       ██       ██       ██     ██
██     ██ ██     ██ ██     ██  ██  ██     ██ ████████  ██     ██ ██████   ██████   ██████   ████████
█████████ ██     ██ ██     ██  ██  ██     ██ ██     ██ ██     ██ ██       ██       ██       ██   ██
██     ██ ██     ██ ██     ██  ██  ██     ██ ██     ██ ██     ██ ██       ██       ██       ██    ██
██     ██  ███████  ████████  ████  ███████  ████████   ███████  ██       ██       ████████ ██     ██
-->

<h3 interface lt="AudioBuffer" id="AudioBuffer">
The {{AudioBuffer}} Interface</h3>

This interface represents a memory-resident audio asset. It can contain one or
more channels with each channel appearing to be 32-bit floating-point
[=linear PCM=] values with a nominal range of \([-1,1]\) but the
values are not limited to this range. Typically, it would be expected
that the length of the
PCM data would be fairly short (usually somewhat less than a minute).
For longer sounds, such as music soundtracks, streaming should be
used with the <{audio}> element and
{{MediaElementAudioSourceNode}}.

An {{AudioBuffer}} may be used by one or more
{{AudioContext}}s, and can be shared between an
{{OfflineAudioContext}} and an
{{AudioContext}}.

{{AudioBuffer}} has four internal slots:

<dl dfn-type=attribute dfn-for="AudioBuffer">
    : <dfn>[[number of channels]]</dfn>
    ::
        The number of audio channels for this {{AudioBuffer}}, which is an unsigned long.

    : <dfn>\[[length]]</dfn>
    ::
        The length of each channel of this {{AudioBuffer}}, which is an unsigned long.

    : <dfn>[[sample rate]]</dfn>
    ::
        The sample-rate, in Hz, of this {{AudioBuffer}}, a float.

    : <dfn>[[internal data]]</dfn>
    ::
        A [=data block=] holding the audio sample data.
</dl>

<pre class="idl">
[Exposed=Window]
interface AudioBuffer {
    constructor (AudioBufferOptions options);
    readonly attribute float sampleRate;
    readonly attribute unsigned long length;
    readonly attribute double duration;
    readonly attribute unsigned long numberOfChannels;
    Float32Array getChannelData (unsigned long channel);
    undefined copyFromChannel (Float32Array destination,
                               unsigned long channelNumber,
                               optional unsigned long bufferOffset = 0);
    undefined copyToChannel (Float32Array source,
                             unsigned long channelNumber,
                             optional unsigned long bufferOffset = 0);
};
</pre>

<h4 id="AudioBuffer-constructors">
Constructors</h4>

<dl dfn-type="constructor" dfn-for="AudioBuffer">
    : <dfn>AudioBuffer(options)</dfn>
    ::
        <div algorithm="new AudioBuffer()">
            1. <span class="synchronous">If any of the values in {{AudioBuffer/constructor()/options!!argument}} lie outside its nominal range, throw a {{NotSupportedError}} exception and abort the following steps.</span>

            1. Let <var>b</var> be a new {{AudioBuffer}} object.
            1. Respectively assign the values of the attributes
                {{AudioBufferOptions/numberOfChannels}}, {{AudioBufferOptions/length}},
                {{AudioBufferOptions/sampleRate}} of the {{AudioBufferOptions}} passed
                in the constructor to the internal slots {{[[number of channels]]}}, {{[[length]]}}, {{[[sample rate]]}}.

            1. Set the internal slot {{[[internal data]]}} of this
                {{AudioBuffer}} to the result of calling <code><a href="https://tc39.github.io/ecma262/#sec-createbytedatablock">
                CreateByteDataBlock</a>({{[[length]]}} * {{[[number of channels]]}})</code>.

                Note: This initializes the underlying storage to zero.

            1. Return <var>b</var>.
        </div>
        <pre class=argumentdef for="AudioBuffer/constructor()">
        options: An {{AudioBufferOptions}} that determine the properties for this {{AudioBuffer}}.
        </pre>
</dl>

<h4 id="AudioBuffer-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioBuffer">
    : <dfn>duration</dfn>
    ::
        Duration of the PCM audio data in seconds.

        This is computed from the {{[[sample rate]]}} and the
        {{[[length]]}} of the {{AudioBuffer}} by performing
        a division between the {{AudioBuffer/[[length]]}} and the
        {{[[sample rate]]}}.

    : <dfn>length</dfn>
    ::
        Length of the PCM audio data in sample-frames. This MUST return
        the value of {{AudioBuffer/[[length]]}}.

    : <dfn>numberOfChannels</dfn>
    ::
        The number of discrete audio channels. This MUST return the value
        of {{[[number of channels]]}}.

    : <dfn>sampleRate</dfn>
    ::
        The sample-rate for the PCM audio data in samples per second.
        This MUST return the value of {{[[sample rate]]}}.
</dl>

<h4 id="AudioBuffer-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AudioBuffer">
    : <dfn>copyFromChannel(destination, channelNumber, bufferOffset)</dfn>
    ::
        The {{AudioBuffer/copyFromChannel()}} method copies the samples from
        the specified channel of the {{AudioBuffer}} to the
        <code>destination</code> array.

        Let <code>buffer</code> be the {{AudioBuffer}} with
        \(N_b\) frames, let \(N_f\) be the number of elements in the
        {{AudioBuffer/copyFromChannel()/destination}} array, and \(k\) be the value of
        {{AudioBuffer/copyFromChannel()/bufferOffset}}. Then the number of frames copied
        from <code>buffer</code> to {{AudioBuffer/copyFromChannel()/destination}} is
        \(\max(0, \min(N_b - k, N_f))\). If this is less than \(N_f\), then the
        remaining elements of {{AudioBuffer/copyFromChannel()/destination}} are not
        modified.

        <pre class=argumentdef for="AudioBuffer/copyFromChannel()">
        destination: The array the channel data will be copied to.
        channelNumber: The index of the channel to copy the data from. If <code>channelNumber</code> is greater or equal than the number of channels of the {{AudioBuffer}}, <span class="synchronous">an {{IndexSizeError}} MUST be thrown</span>.
        bufferOffset: An optional offset, defaulting to 0.  Data from the {{AudioBuffer}} starting at this offset is copied to the {{AudioBuffer/copyFromChannel()/destination}}.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>copyToChannel(source, channelNumber, bufferOffset)</dfn>
    ::
        The {{AudioBuffer/copyToChannel()}} method copies the samples to
        the specified channel of the {{AudioBuffer}} from the
        <code>source</code> array.

        A {{UnknownError}} may be thrown if
        {{AudioBuffer/copyToChannel()/source}} cannot be
        copied to the buffer.

        Let <code>buffer</code> be the {{AudioBuffer}} with
        \(N_b\) frames, let \(N_f\) be the number of elements in the
        {{AudioBuffer/copyToChannel()/source}} array, and \(k\) be the value of
        {{AudioBuffer/copyToChannel()/bufferOffset}}. Then the number of frames copied
        from {{AudioBuffer/copyToChannel()/source}} to the <code>buffer</code> is
        \(\max(0, \min(N_b - k, N_f))\). If this is less than \(N_f\), then the
        remaining elements of <code>buffer</code> are not
        modified.

        <pre class=argumentdef for="AudioBuffer/copyToChannel()">
        source: The array the channel data will be copied from.
        channelNumber: The index of the channel to copy the data to. If <code>channelNumber</code> is greater or equal than the number of channels of the {{AudioBuffer}}, <span class="synchronous">an {{IndexSizeError}} MUST be thrown</span>.
        bufferOffset: An optional offset, defaulting to 0.  Data from the {{AudioBuffer/copyToChannel()/source}} is copied to the {{AudioBuffer}} starting at this offset.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>getChannelData(channel)</dfn>
    ::
        According to the rules described in <a href="#acquire-the-content">acquire the content</a>
        either allow [=ArrayBufferView/write|writing=] into
        or [=get a copy of the buffer source|getting a copy of=]
        the bytes stored in {{[[internal data]]}} in a new
        {{Float32Array}}

        A {{UnknownError}} may be thrown if the {{[[internal
        data]]}} or the new {{Float32Array}} cannot be
        created.

        <pre class=argumentdef for="AudioBuffer/getChannelData()">
        channel: This parameter is an index representing the particular channel to get data for. An index value of 0 represents the first channel. <span class="synchronous">This index value MUST be less than {{[[number of channels]]}} or an {{IndexSizeError}} exception MUST be thrown.</span>
        </pre>

        <div>
            <em>Return type:</em> {{Float32Array}}
        </div>
</dl>

Note: The methods {{AudioBuffer/copyToChannel()}} and
{{AudioBuffer/copyFromChannel()}} can be used to fill part of an array by
passing in a {{Float32Array}} that's a view onto the larger
array. When reading data from an {{AudioBuffer}}'s channels, and
the data can be processed in chunks, {{AudioBuffer/copyFromChannel()}}
should be preferred to calling {{AudioBuffer/getChannelData()}} and
accessing the resulting array, because it may avoid unnecessary
memory allocation and copying.

An internal operation <a href="#acquire-the-content">acquire the
contents of an AudioBuffer</a> is invoked when the
contents of an {{AudioBuffer}} are needed by some API
implementation. This operation returns immutable channel data to the
invoker.

<div algorithm="acquire the content of an AudioBuffer">
    When an <dfn lt="acquire the content|acquire the contents of an AudioBuffer">acquire the content</dfn>
    operation occurs on an {{AudioBuffer}}, run the following steps:

    
    1. If any of the {{AudioBuffer}}'s {{ArrayBuffer}}s are
        [=BufferSource/detached=], return `true`, abort these steps, and
        return a zero-length channel data buffer to the invoker.

    2. [=ArrayBuffer/Detach=] all {{ArrayBuffer}}s for arrays previously returned
        by {{AudioBuffer/getChannelData()}} on this {{AudioBuffer}}.

        Note: Because {{AudioBuffer}} can only be created via
        {{BaseAudioContext/createBuffer()}} or via the {{AudioBuffer}} constructor, this
        cannot throw.

    3. Retain the underlying {{[[internal data]]}} from those
        {{ArrayBuffer}}s and return references to them to the
        invoker.

    4. Attach {{ArrayBuffer}}s containing copies of the data to
        the {{AudioBuffer}}, to be returned by the next call to
        {{AudioBuffer/getChannelData()}}.
</div>

The [=acquire the contents of an AudioBuffer=] operation is invoked in the following cases:

* When {{AudioBufferSourceNode/start()|AudioBufferSourceNode.start}}  is called, it
    <a href="#acquire-the-content">acquires the contents</a> of the
    node's {{AudioBufferSourceNode/buffer}}. If the operation fails, nothing is
    played.

* When the {{AudioBufferSourceNode/buffer}} of an {{AudioBufferSourceNode}}
    is set and {{AudioBufferSourceNode/start()|AudioBufferSourceNode.start}} has been
    previously called, the setter <a href="#acquire-the-content">acquires
    the content</a> of the {{AudioBuffer}}. If the operation fails,
    nothing is played.

* When a {{ConvolverNode}}'s {{ConvolverNode/buffer}} is set to an
    {{AudioBuffer}} it <a href="#acquire-the-content">acquires the content</a> of
    the {{AudioBuffer}}.

* When the dispatch of an {{AudioProcessingEvent}} completes, it
    <a href="#acquire-the-content">acquires the contents</a> of its
    {{AudioProcessingEvent/outputBuffer}}.

Note: This means that {{AudioBuffer/copyToChannel()}} cannot be used to change
the content of an {{AudioBuffer}} currently in use by an
{{AudioNode}} that has [=acquire the content|acquired the content of an AudioBuffer=]
since the {{AudioNode}} will continue to use the data previously
acquired.

<h4 dictionary id="AudioBufferOptions">
{{AudioBufferOptions}}</h4>

This specifies the options to use in constructing an
{{AudioBuffer}}. The {{AudioBufferOptions/length}} and {{AudioBufferOptions/sampleRate}} members are
required.

<pre class="idl">
dictionary AudioBufferOptions {
    unsigned long numberOfChannels = 1;
    required unsigned long length;
    required float sampleRate;
};
</pre>

<h5 id="dictionary-audiobufferoptions-members">
Dictionary {{AudioBufferOptions}} Members</h5>

The allowed values for the members of this dictionary are constrained.  See {{BaseAudioContext/createBuffer()}}.

<dl dfn-type=dict-member dfn-for="AudioBufferOptions">
    : <dfn>length</dfn>
    ::
        The length in sample frames of the buffer. See {{BaseAudioContext/createBuffer()/length}} for constraints.

    : <dfn>numberOfChannels</dfn>
    ::
        The number of channels for the buffer.  See {{BaseAudioContext/createBuffer()/numberOfChannels}} for constraints.

    : <dfn>sampleRate</dfn>
    ::
        The sample rate in Hz for the buffer.  See {{BaseAudioContext/createBuffer()/sampleRate}} for constraints.
</dl>


<!--
   ███    ██     ██ ████████  ████  ███████  ██    ██  ███████  ████████  ████████
  ██ ██   ██     ██ ██     ██  ██  ██     ██ ███   ██ ██     ██ ██     ██ ██
 ██   ██  ██     ██ ██     ██  ██  ██     ██ ████  ██ ██     ██ ██     ██ ██
██     ██ ██     ██ ██     ██  ██  ██     ██ ██ ██ ██ ██     ██ ██     ██ ██████
█████████ ██     ██ ██     ██  ██  ██     ██ ██  ████ ██     ██ ██     ██ ██
██     ██ ██     ██ ██     ██  ██  ██     ██ ██   ███ ██     ██ ██     ██ ██
██     ██  ███████  ████████  ████  ███████  ██    ██  ███████  ████████  ████████
-->


<h3 interface lt="AudioNode" id="AudioNode">
The {{AudioNode}} Interface</h3>

{{AudioNode}}s are the building blocks of an {{AudioContext}}. This interface
represents audio sources, the audio destination, and intermediate
processing modules. These modules can be connected together to form
<a href="#ModularRouting">processing graphs</a> for rendering audio
to the audio hardware. Each node can have <a>inputs</a> and/or
<a>outputs</a>. A <a>source node</a> has no inputs and a single
output. Most processing nodes such as filters will have one input and
one output. Each type of {{AudioNode}} differs in the
details of how it processes or synthesizes audio. But, in general, an
{{AudioNode}} will process its inputs (if it has
any), and generate audio for its outputs (if it has any).

Each output has one or more channels. The exact number of channels
depends on the details of the specific {{AudioNode}}.

An output may connect to one or more {{AudioNode}}
inputs, thus <em>fan-out</em> is supported. An input initially has no
connections, but may be connected from one or more {{AudioNode}}
outputs, thus <em>fan-in</em> is supported. When the
<code>connect()</code> method is called to connect an output of an
{{AudioNode}} to an input of an {{AudioNode}}, we call that a
<dfn>connection</dfn> to the input.

Each {{AudioNode}} <dfn>input</dfn> has a specific number of
channels at any given time. This number can change depending on the
<a>connection</a>(s) made to the input. If the input has no
connections then it has one channel which is silent.

For each <a>input</a>, an {{AudioNode}} performs a
mixing of all connections to that input.
Please see <a href="#channel-up-mixing-and-down-mixing"></a>
for normative requirements and details.

The processing of inputs and the internal operations of an
{{AudioNode}} take place continuously with respect to
{{AudioContext}} time, regardless of whether the node has
connected outputs, and regardless of whether these outputs ultimately
reach an {{AudioContext}}'s {{AudioDestinationNode}}.

<pre class="idl">
[Exposed=Window]
interface AudioNode : EventTarget {
    AudioNode connect (AudioNode destinationNode,
                       optional unsigned long output = 0,
                       optional unsigned long input = 0);
    undefined connect (AudioParam destinationParam, optional unsigned long output = 0);
    undefined disconnect ();
    undefined disconnect (unsigned long output);
    undefined disconnect (AudioNode destinationNode);
    undefined disconnect (AudioNode destinationNode, unsigned long output);
    undefined disconnect (AudioNode destinationNode,
                          unsigned long output,
                          unsigned long input);
    undefined disconnect (AudioParam destinationParam);
    undefined disconnect (AudioParam destinationParam, unsigned long output);
    readonly attribute BaseAudioContext context;
    readonly attribute unsigned long numberOfInputs;
    readonly attribute unsigned long numberOfOutputs;
    attribute unsigned long channelCount;
    attribute ChannelCountMode channelCountMode;
    attribute ChannelInterpretation channelInterpretation;
};
</pre>

<h4 id="AudioNode-creation">
AudioNode Creation</h4>

{{AudioNode}}s can be created in two ways: by using the
constructor for this particular interface, or by using the
<dfn>factory method</dfn> on the {{BaseAudioContext}} or
{{AudioContext}}.

The {{BaseAudioContext}} passed as first argument of the
constructor of an {{AudioNode}}s is called the <dfn id="associated">associated {{BaseAudioContext}}</dfn> of the
{{AudioNode}} to be created. Similarly, when using the factory
method, the <a>associated <code>BaseAudioContext</code></a> of the
{{AudioNode}} is the {{BaseAudioContext}} this factory method
is called on.

<div algorithm="AudioNode factory method">
    To create a new {{AudioNode}} of a particular type <var>n</var>
    using its <a>factory method</a>, called on a
    {{BaseAudioContext}} <var>c</var>, execute these steps:

    1. Let <var>node</var> be a new object of type <var>n</var>.

    2. Let <var>option</var> be a dictionary of the type <a lt="associated option
        object">associated</a> to the interface <a lt="associated interface">
        associated</a> to this factory method.

    3. For each parameter passed to the factory method, set the
        dictionary member of the same name on <var>option</var> to the
        value of this parameter.

    4. Call the constructor for <var>n</var> on <var>node</var> with
        <var>c</var> and <var>option</var> as arguments.

    5. Return <var>node</var>
</div>

<div algorithm="initialize an AudioNode">
    <dfn id="audionode-constructor-init">Initializing</dfn> an object
    <var>o</var> that inherits from {{AudioNode}} means executing the following
    steps, given the arguments <var>context</var> and <var>dict</var> passed to
    the constructor of this interface.

    1. Set <var>o</var>'s associated {{BaseAudioContext}} to <var>context</var>.

    2. Set its value for {{AudioNode/numberOfInputs}},
        {{AudioNode/numberOfOutputs}}, {{AudioNode/channelCount}},
        {{AudioNode/channelCountMode}}, {{AudioNode/channelInterpretation}} to the
        default value for this
        specific interface outlined in the section for each {{AudioNode}}.

    3. For each member of <var>dict</var> passed in, execute these steps, with
        <var>k</var> the key of the member, and <var>v</var> its value. If any
        exceptions is thrown when executing these steps, abort the iteration and
        propagate the exception to the caller of the algorithm (constructor or
        factory method).

        1. If <var>k</var> is the name of an {{AudioParam}} on this
            interface, set the {{AudioParam/value}}
            attribute of this {{AudioParam}} to <var>v</var>.

        2. Else if <var>k</var> is the name of an attribute on this
            interface, set the object associated with this attribute to
            <var>v</var>.
</div>

The <dfn>associated interface</dfn> for a factory method is the
interface of the objects that are returned from this method. The
<dfn>associated option object</dfn> for an interface is the option
object that can be passed to the constructor for this interface.

{{AudioNode}}s are {{EventTarget}}s, as described in [[!DOM]].
This means that it is possible to dispatch events to
{{AudioNode}}s the same way that other {{EventTarget}}s
accept events.

<pre class="idl">
enum ChannelCountMode {
    "max",
    "clamped-max",
    "explicit"
};
</pre>

The {{ChannelCountMode}}, in conjuction with the node's
{{AudioNode/channelCount}} and {{AudioNode/channelInterpretation}} values, is used to determine
the <dfn>computedNumberOfChannels</dfn> that controls how inputs to a
node are to be mixed. The <a>computedNumberOfChannels</a> is
determined as shown below. See <a href="#channel-up-mixing-and-down-mixing"></a> for more information on how
mixing is to be done.

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="ChannelCountMode">
    <caption>{{ChannelCountMode}} enumeration description</caption>
    <thead>
    <tr>
        <th>Enum value</th><th>Description</th>
    <tbody>
    <tr>
        <td>"<dfn>max</dfn>"
        <td>
            <a>computedNumberOfChannels</a> is the maximum of the number of
            channels of all connections to an input. In this mode
            {{AudioNode/channelCount}} is ignored.
    <tr>
        <td>"<dfn>clamped-max</dfn>"
        <td>
            <a>computedNumberOfChannels</a> is determined as for "{{ChannelCountMode/max}}"
            and then clamped to a maximum value of the given
            {{AudioNode/channelCount}}.
    <tr>
        <td>"<dfn>explicit</dfn>"
        <td>
            <a>computedNumberOfChannels</a> is the exact value as specified
            by the {{AudioNode/channelCount}}.
</table>
</div>

<pre class="idl">
enum ChannelInterpretation {
    "speakers",
    "discrete"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="ChannelInterpretation">
    <caption>{{ChannelInterpretation}} enumeration description</caption>
    <thead>
    <tr>
        <th>Enum value</th><th>Description</th>
    <tbody>
    <tr>
        <td>"<dfn>speakers</dfn>"
        <td>
            use <a href="#UpMix-sub">up-mix equations</a> or <a href="#down-mix">down-mix equations</a>. In cases where the number of
            channels do not match any of these basic speaker layouts, revert
            to "{{ChannelInterpretation/discrete}}".
    <tr>
        <td>"<dfn>discrete</dfn>"
        <td>
            Up-mix by filling channels until they run out then zero out
            remaining channels. Down-mix by filling as many channels as
            possible, then dropping remaining channels.
</table>
</div>

<h4 id="AudioNode-tail">AudioNode Tail-Time</h4>

An {{AudioNode}} can have a <dfn>tail-time</dfn>. This means that even when the
{{AudioNode}} is fed silence, the output can be non-silent.

{{AudioNode}}s have a non-zero tail-time if they have internal processing state
such that input in the past affects the future output. {{AudioNode}}s
may continue to produce non-silent output for the calculated tail-time even
after the input transitions from non-silent to silent.

<h4 id="AudioNode-actively-processing">AudioNode Lifetime</h4>

{{AudioNode}} can be <dfn id="actively-processing">actively processing</dfn>
during a <a>render quantum</a>, if any of the following conditions hold.

- An {{AudioScheduledSourceNode}} is [=actively processing=] if and only if it
    is [=playing=] for at least part of the current rendering quantum.
- A {{MediaElementAudioSourceNode}} is [=actively processing=] if and only if its
    {{MediaElementAudioSourceNode/mediaElement}} is playing for at least part of
    the current rendering quantum.
- A {{MediaStreamAudioSourceNode}} or a {{MediaStreamTrackAudioSourceNode}} are
    [=actively processing=] when the associated
    {{MediaStreamTrack}} object has a
    <code>readyState</code> attribute equal to <code>"live"</code>, a
    <code>muted</code> attribute equal to <code>false</code> and an
    <code>enabled</code> attribute equal to <code>true</code>.
- A {{DelayNode}} in a cycle is [=actively processing=] only when the absolute value
    of any output sample for the current [=render quantum=] is greater than or equal
    to \( 2^{-126} \).
- A {{ScriptProcessorNode}} is [=actively processing=] when its input or output is
    connected.
- An {{AudioWorkletNode}} is [=actively processing=] when its
    {{AudioWorkletProcessor}}'s {{[[callable process]]}} returns <code>true</code>
    and either its [=active source=] flag is <code>true</code> or any
    {{AudioNode}} connected to one of its inputs is [=actively processing=].
- All other {{AudioNode}}s start [=actively processing=] when any
    {{AudioNode}} connected to one of its inputs is [=actively processing=], and
    stops [=actively processing=] when the input that was received from other
    [=actively processing=] {{AudioNode}} no longer affects the output.

Note: This takes into account {{AudioNode}}s that have a [=tail-time=].

{{AudioNode}}s that are not [=actively processing=] output a single channel of
silence.


<h4 id="AudioNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioNode">
    : <dfn>channelCount</dfn>
    ::
        {{AudioNode/channelCount}} is the number of channels used when
        up-mixing and down-mixing connections to any inputs to the
        node. The default value is 2 except for specific nodes where
        its value is specially determined. This attribute has no effect
        for nodes with no inputs. <span class="synchronous">If this
        value is set to zero or to a value greater than the
        implementation's maximum number of channels the implementation
        MUST throw a {{NotSupportedError}} exception.</span>

        In addition, some nodes have additional <dfn dfn>channelCount
        constraints</dfn> on the possible values for the channel count:

        :  {{AudioDestinationNode}}
        ::
            The behavior depends on whether the destination node is the
            destination of an {{AudioContext}} or
            {{OfflineAudioContext}}:

            : {{AudioContext}}
            ::
                The channel count MUST be between 1 and
                {{AudioDestinationNode/maxChannelCount}}. An <span class="synchronous">{{IndexSizeError}} exception MUST
                be thrown for any attempt to set the count outside this
                range</span>.
            : {{OfflineAudioContext}}
            ::
                The channel count cannot be changed. An <span class="synchronous">{{InvalidStateError}} exception
                MUST be thrown for any attempt to change the
                value.</span>

        : {{AudioWorkletNode}}
        ::
            See [[#configuring-channels-with-audioworkletnodeoptions]]
            Configuring Channels with {{AudioWorkletNodeOptions}}.

        : {{ChannelMergerNode}}
        ::
            The channel count cannot be changed, and an <span class="synchronous">{{InvalidStateError}} exception MUST
            be thrown for any attempt to change the value.</span>

        : {{ChannelSplitterNode}}
        ::
            The channel count cannot be changed, and an <span class="synchronous">{{InvalidStateError}} exception MUST
            be thrown for any attempt to change the value.</span>

        : {{ConvolverNode}}
        ::
            The channel count cannot be greater than two, and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to change it to a
            value greater than two.</span>

        : {{DynamicsCompressorNode}}
        ::
            The channel count cannot be greater than two, and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to change it to a
            value greater than two.</span>

        : {{PannerNode}}
        ::
            The channel count cannot be greater than two, and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to change it to a
            value greater than two.</span>

        : {{ScriptProcessorNode}}
        ::
            The channel count cannot be changed, and an <span class="synchronous">{{NotSupportedError}} exception MUST
            be thrown for any attempt to change the value.</span>

        : {{StereoPannerNode}}
        ::
            The channel count cannot be greater than two, and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to change it to a
            value greater than two.</span>

        See [[#channel-up-mixing-and-down-mixing]] for more information on this attribute.

    : <dfn>channelCountMode</dfn>
    ::
        {{AudioNode/channelCountMode}} determines how channels will be counted
        when up-mixing and down-mixing connections to any inputs to the
        node. The default value is "{{ChannelCountMode/max}}". This attribute has no effect for nodes with no inputs.

        In addition, some nodes have additional <dfn dfn>channelCountMode
        constraints</dfn> on the possible values for the channel count
        mode:

        : {{AudioDestinationNode}}
        ::
            If the {{AudioDestinationNode}} is the {{BaseAudioContext/destination}} node of an
            {{OfflineAudioContext}}, then the channel count mode
            cannot be changed. An <span class="synchronous">{{InvalidStateError}} exception MUST
            be thrown for any attempt to change the value.</span>
        : {{ChannelMergerNode}}
        ::
            The channel count mode cannot be changed from "{{ChannelCountMode/explicit}}" and
            an <span class="synchronous">{{InvalidStateError}}
            exception MUST be thrown for any attempt to change the
            value.</span>


        : {{ChannelSplitterNode}}
        ::
            The channel count mode cannot be changed from "{{ChannelCountMode/explicit}}" and
            an <span class="synchronous">{{InvalidStateError}}
            exception MUST be thrown for any attempt to change the
            value.</span>

        : {{ConvolverNode}}
        ::
            The channel count mode cannot be set to "{{ChannelCountMode/max}}", and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to set it to
            "{{ChannelCountMode/max}}".</span>

        : {{DynamicsCompressorNode}}
        ::
            The channel count mode cannot be set to "{{ChannelCountMode/max}}", and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to set it to
            "{{ChannelCountMode/max}}".</span>

        : {{PannerNode}}
        ::
            The channel count mode cannot be set to "{{ChannelCountMode/max}}", and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to set it to
            "{{ChannelCountMode/max}}".</span>

        : {{ScriptProcessorNode}}
        ::
            The channel count mode cannot be changed from "{{ChannelCountMode/explicit}}" and
            an <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to change the
            value.</span>

        : {{StereoPannerNode}}
        ::
            The channel count mode cannot be set to "{{ChannelCountMode/max}}", and a
            <span class="synchronous">{{NotSupportedError}}
            exception MUST be thrown for any attempt to set it to
            "{{ChannelCountMode/max}}".</span>

        See the <a href="#channel-up-mixing-and-down-mixing"></a>
        section for more information on this attribute.

    : <dfn>channelInterpretation</dfn>
    ::
        {{AudioNode/channelInterpretation}} determines how individual channels
        will be treated when up-mixing and down-mixing connections to
        any inputs to the node. The default value is "{{ChannelInterpretation/speakers}}". This attribute has no effect for nodes
        with no inputs.

        In addition, some nodes have additional
        <dfn dfn>channelInterpretation constraints</dfn> on the possible
        values for the channel interpretation:

        :  {{ChannelSplitterNode}}
        ::
            The channel intepretation can not be changed from
            "{{ChannelInterpretation/discrete}}" and a
            <span class="synchronous">{{InvalidStateError}}
            exception MUST be thrown for any attempt to change the
            value.</span>

        See [[#channel-up-mixing-and-down-mixing]] for more information on this attribute.

    : <dfn>context</dfn>
    ::
        The {{BaseAudioContext}} which owns this {{AudioNode}}.

    : <dfn>numberOfInputs</dfn>
    ::
        The number of inputs feeding into the {{AudioNode}}. For
        <dfn dfn>source nodes</dfn>, this will be 0. This attribute is
        predetermined for many {{AudioNode}} types, but some
        {{AudioNode}}s, like the {{ChannelMergerNode}} and the
        {{AudioWorkletNode}}, have variable number of inputs.

    : <dfn>numberOfOutputs</dfn>
    ::
        The number of outputs coming out of the {{AudioNode}}. This
        attribute is predetermined for some {{AudioNode}} types, but
        can be variable, like for the {{ChannelSplitterNode}} and the
        {{AudioWorkletNode}}.
</dl>

<h4 id="AudioNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AudioNode">
    : <dfn>connect(destinationNode, output, input)</dfn>
    ::
        There can only be one connection between a given output of one
        specific node and a given input of another specific node.
        Multiple connections with the same termini are ignored.

        <div class=example>
            For example:

            <pre highlight="js">
                nodeA.connect(nodeB);
                nodeA.connect(nodeB);
            </pre>

            will have the same effect as

            <pre highlight="js">
                nodeA.connect(nodeB);
            </pre>
        </div>

        This method returns <code>destination</code>
        {{AudioNode}} object.

        <pre class=argumentdef for="AudioNode/connect(destinationNode, output, input)">
            destinationNode: The <code>destination</code> parameter is the {{AudioNode}} to connect to. <span class="synchronous">If the <code>destination</code> parameter is an {{AudioNode}} that has been created using another {{AudioContext}}, an {{InvalidAccessError}} MUST be thrown</span>. That is, {{AudioNode}}s cannot be shared between {{AudioContext}}s. Multiple {{AudioNode}}s can be connected to the same {{AudioNode}}, this is described in [[#channel-up-mixing-and-down-mixing|Channel Upmixing and down mixing]] section.
            output: The <code>output</code> parameter is an index describing which output of the {{AudioNode}} from which to connect. <span class="synchronous">If this parameter is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span> It is possible to connect an {{AudioNode}} output to more than one input with multiple calls to connect(). Thus, "fan-out" is supported.
            input:  The <code>input</code> parameter is an index describing which input of the destination {{AudioNode}} to connect to. <span class="synchronous">If this parameter is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span> It is possible to connect an {{AudioNode}} to another {{AudioNode}} which creates a <dfn dfn for>cycle</dfn>: an {{AudioNode}} may connect to another {{AudioNode}}, which in turn connects back to the input or {{AudioParam}} of the first {{AudioNode}}.
        </pre>

        <div>
            <em>Return type:</em> {{AudioNode}}
        </div>

    : <dfn>connect(destinationParam, output)</dfn>
    ::
        Connects the {{AudioNode}} to an
        {{AudioParam}}, controlling the parameter value
        with an <a>a-rate</a> signal.

        It is possible to connect an {{AudioNode}}
        output to more than one {{AudioParam}} with
        multiple calls to connect(). Thus, "fan-out" is supported.

        It is possible to connect more than one
        {{AudioNode}} output to a single
        {{AudioParam}} with multiple calls to
        connect(). Thus, "fan-in" is supported.

        An {{AudioParam}} will take the rendered audio
        data from any {{AudioNode}} output connected to
        it and <a href="#down-mix">convert it to mono</a> by
        down-mixing if it is not already mono, then mix it together
        with other such outputs and finally will mix with the
        <em>intrinsic</em> parameter value (the <code>value</code> the
        {{AudioParam}} would normally have without any
        audio connections), including any timeline changes scheduled
        for the parameter.

        The down-mixing to mono is equivalent to the down-mixing for an
        {{AudioNode}} with {{AudioNode/channelCount}} = 1,
        {{AudioNode/channelCountMode}} = "{{ChannelCountMode/explicit}}", and
        {{AudioNode/channelInterpretation}} = "{{ChannelInterpretation/speakers}}".

        There can only be one connection between a given output of one
        specific node and a specific {{AudioParam}}.
        Multiple connections with the same termini are ignored.

        <div class=example>
            For example:

            <pre highlight="js">
                nodeA.connect(param);
                nodeA.connect(param);
            </pre>

            will have the same effect as

            <pre highlight="js">
                nodeA.connect(param);
            </pre>
        </div>

        <pre class=argumentdef for="AudioNode/connect(destinationParam, output)">
            destinationParam: The <code>destination</code> parameter is the {{AudioParam}} to connect to. This method does not return the <code>destination</code> {{AudioParam}} object. <span class="synchronous">If {{AudioNode/connect(destinationParam, output)/destinationParam}} belongs to an {{AudioNode}} that belongs to a {{BaseAudioContext}} that is different from the {{BaseAudioContext}} that has created the {{AudioNode}} on which this method was called, an {{InvalidAccessError}} MUST be thrown.</span>
            output: The <code>output</code> parameter is an index describing which output of the {{AudioNode}} from which to connect. <span class="synchronous">If the <code>parameter</code> is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span>
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>disconnect()</dfn>
    ::
        Disconnects all outgoing connections from the
        {{AudioNode}}.

        <div>
            <em>No parameters.</em>
        </div>
        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>disconnect(output)</dfn>
    ::
        Disconnects a single output of the
        {{AudioNode}} from any other
        {{AudioNode}} or {{AudioParam}}
        objects to which it is connected.

        <pre class=argumentdef for="AudioNode/disconnect(output)">
            output:  This parameter is an index describing which output of the {{AudioNode}} to disconnect. It disconnects all outgoing connections from the given output. <span class="synchronous">If this parameter is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span>
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>disconnect(destinationNode)</dfn>
    ::
        Disconnects all outputs of the {{AudioNode}}
        that go to a specific destination
        {{AudioNode}}.

        <pre class=argumentdef for="AudioNode/disconnect(destinationNode)">
            destinationNode: The <code>destinationNode</code> parameter is the {{AudioNode}} to disconnect. It disconnects all outgoing connections to the given <code>destinationNode</code>. <span class="synchronous">If there is no connection to the <code>destinationNode</code>, an {{InvalidAccessError}} exception MUST be thrown.</span>
        </pre>
        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>disconnect(destinationNode, output)</dfn>
    ::
        Disconnects a specific output of the
        {{AudioNode}} from any and all inputs of some
        destination {{AudioNode}}.

        <pre class=argumentdef for="AudioNode/disconnect(destinationNode, output)">
            destinationNode: The <code>destinationNode</code> parameter is the {{AudioNode}} to disconnect. <span class="synchronous">If there is no connection to the <code>destinationNode</code> from the given output, an {{InvalidAccessError}} exception MUST be thrown.</span>
            output: The <code>output</code> parameter is an index describing which output of the {{AudioNode}} from which to disconnect. <span class="synchronous">If this parameter is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span>
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>disconnect(destinationNode, output, input)</dfn>
    ::
        Disconnects a specific output of the
        {{AudioNode}} from a specific input of some
        destination {{AudioNode}}.

        <pre class=argumentdef for="AudioNode/disconnect(destinationNode, output, input)">
            destinationNode: The <code>destinationNode</code> parameter is the {{AudioNode}} to disconnect. <span class="synchronous">If there is no connection to the <code>destinationNode</code> from the given output to the given input, an {{InvalidAccessError}} exception MUST be thrown.</span>
            output: The <code>output</code> parameter is an index describing which output of the {{AudioNode}} from which to disconnect. <span class="synchronous">If this parameter is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span>
            input: The <code>input</code> parameter is an index describing which input of the destination {{AudioNode}} to disconnect. <span class="synchronous">If this parameter is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span>
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>disconnect(destinationParam)</dfn>
    ::
        Disconnects all outputs of the {{AudioNode}}
        that go to a specific destination
        {{AudioParam}}. The contribution of this
        {{AudioNode}} to the computed parameter value
        goes to 0 when this operation takes effect. The intrinsic
        parameter value is not affected by this operation.

        <pre class=argumentdef for="AudioNode/disconnect(destinationParam)">
            destinationParam: The <code>destinationParam</code> parameter is the {{AudioParam}} to disconnect. <span class="synchronous">If there is no connection to the <code>destinationParam</code>, an {{InvalidAccessError}} exception MUST be thrown.</span>
        </pre>
        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>disconnect(destinationParam, output)</dfn>
    ::
        Disconnects a specific output of the
        {{AudioNode}} from a specific destination
        {{AudioParam}}. The contribution of this
        {{AudioNode}} to the computed parameter value
        goes to 0 when this operation takes effect. The intrinsic
        parameter value is not affected by this operation.

        <pre class=argumentdef for="AudioNode/disconnect(destinationParam, output)">
            destinationParam: The <code>destinationParam</code> parameter is the {{AudioParam}} to disconnect. <span class="synchronous">If there is no connection to the <code>destinationParam</code>, an {{InvalidAccessError}} exception MUST be thrown.</span>
            output: The <code>output</code> parameter is an index describing which output of the {{AudioNode}} from which to disconnect. <span class="synchronous">If the <code>parameter</code> is out-of-bounds, an {{IndexSizeError}} exception MUST be thrown.</span>
        </pre>
        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>

<h4 dictionary id="AudioNodeOptions">
{{AudioNodeOptions}}</h4>

This specifies the options that can be used in constructing all
{{AudioNode}}s. All members are optional. However, the specific
values used for each node depends on the actual node.

<pre class="idl">
dictionary AudioNodeOptions {
    unsigned long channelCount;
    ChannelCountMode channelCountMode;
    ChannelInterpretation channelInterpretation;
};
</pre>

<h5 id="dictionary-audionodeoptions-members">
Dictionary {{AudioNodeOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="AudioNodeOptions">
    : <dfn>channelCount</dfn>
    :: Desired number of channels for the {{AudioNode/channelCount}} attribute.

    : <dfn>channelCountMode</dfn>
    :: Desired mode for the {{AudioNode/channelCountMode}} attribute.

    : <dfn>channelInterpretation</dfn>
    :: Desired mode for the {{AudioNode/channelInterpretation}} attribute.
</dl>

<!--
   ███    ██     ██ ████████  ████  ███████  ████████     ███    ████████     ███    ██     ██
  ██ ██   ██     ██ ██     ██  ██  ██     ██ ██     ██   ██ ██   ██     ██   ██ ██   ███   ███
 ██   ██  ██     ██ ██     ██  ██  ██     ██ ██     ██  ██   ██  ██     ██  ██   ██  ████ ████
██     ██ ██     ██ ██     ██  ██  ██     ██ ████████  ██     ██ ████████  ██     ██ ██ ███ ██
█████████ ██     ██ ██     ██  ██  ██     ██ ██        █████████ ██   ██   █████████ ██     ██
██     ██ ██     ██ ██     ██  ██  ██     ██ ██        ██     ██ ██    ██  ██     ██ ██     ██
██     ██  ███████  ████████  ████  ███████  ██        ██     ██ ██     ██ ██     ██ ██     ██
-->

<h3 interface lt="AudioParam" id="AudioParam">
The {{AudioParam}} Interface</h3>

{{AudioParam}} controls an individual aspect of an
{{AudioNode}}'s functionality, such as volume. The
parameter can be set immediately to a particular value using the
<code>value</code> attribute. Or, value changes can be scheduled to
happen at very precise times (in the coordinate system of
{{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute), for envelopes, volume
fades, LFOs, filter sweeps, grain windows, etc. In this way,
arbitrary timeline-based automation curves can be set on any
{{AudioParam}}. Additionally, audio signals from the
outputs of {{AudioNode}}s can be connected to an
{{AudioParam}}, summing with the <em>intrinsic</em>
parameter value.

Some synthesis and processing {{AudioNode}}s have
{{AudioParam}}s as attributes whose values MUST be taken
into account on a per-audio-sample basis. For other
{{AudioParam}}s, sample-accuracy is not important and the
value changes can be sampled more coarsely. Each individual
{{AudioParam}} will specify that it is either an
<a>a-rate</a> parameter which means that its values MUST be taken
into account on a per-audio-sample basis, or it is a <a>k-rate</a>
parameter.

Implementations MUST use block processing, with each
{{AudioNode}} processing one <a>render quantum</a>.

For each <a>render quantum</a>,
the value of a <dfn id="k-rate">k-rate</dfn> parameter MUST be sampled at the time of the
very first sample-frame, and that value MUST be used for the entire
block. <dfn id="a-rate">a-rate</dfn> parameters MUST be sampled for
each sample-frame of the block.
Depending on the {{AudioParam}}, its rate can be controlled by setting
the {{AudioParam/automationRate}} attribute to either
"{{AutomationRate/a-rate}}" or "{{AutomationRate/k-rate}}".  See the
description of the individual {{AudioParam}}s for further details.

Each {{AudioParam}} includes {{AudioParam/minValue}} and {{AudioParam/maxValue}} attributes that together form
the <dfn>simple nominal range</dfn> for the parameter. In effect,
value of the parameter is clamped to the range \([\mathrm{minValue},
\mathrm{maxValue}]\). See [[#computation-of-value]] for full details.

For many {{AudioParam}}s the {{AudioParam/minValue}} and {{AudioParam/maxValue}} is intended to be set to the maximum
possible range. In this case, {{AudioParam/maxValue}} should be set to the
<dfn>most-positive-single-float</dfn> value, which is 3.4028235e38.
(However, in JavaScript which only supports IEEE-754 double precision
float values, this must be written as 3.4028234663852886e38.)
Similarly, {{AudioParam/minValue}} should be set
to the <dfn>most-negative-single-float</dfn> value, which is the
negative of the <a>most-positive-single-float</a>: -3.4028235e38.
(Similarly, this must be written in JavaScript as
-3.4028234663852886e38.)

An {{AudioParam}} maintains a list of zero or more <dfn id="dfn-automation-event">automation events</dfn>. Each automation event
specifies changes to the parameter's value over a specific time
range, in relation to its <dfn>automation event time</dfn> in the
time coordinate system of the {{AudioContext}}'s
{{BaseAudioContext/currentTime}} attribute. The
list of automation events is maintained in ascending order of
automation event time.

The behavior of a given automation event is a function of the
{{AudioContext}}'s current time, as well as the automation event
times of this event and of adjacent events in the list. The following
<dfn id="dfn-automation-method" lt="automation method">automation methods</dfn> change the
event list by adding a new event to the event list, of a type
specific to the method:

* {{AudioParam/setValueAtTime()}} - <code>SetValue</code>
* {{AudioParam/linearRampToValueAtTime()}} - <code>LinearRampToValue</code>
* {{AudioParam/exponentialRampToValueAtTime()}} - <code>ExponentialRampToValue</code>
* {{AudioParam/setTargetAtTime()}} - <code>SetTarget</code>
* {{AudioParam/setValueCurveAtTime()}} - <code>SetValueCurve</code>

The following rules will apply when calling these methods:

* <a>Automation event times</a> are
    not quantized with respect to the prevailing sample rate. Formulas
    for determining curves and ramps are applied to the exact numerical
    times given when scheduling events.

* If one of these events is added at a time where there is already
    one or more events, then it will be placed in the list after them,
    but before events whose times are after the event.

* <span class="synchronous">If <a
    data-link-for="AudioParam">setValueCurveAtTime()</a> is called for time \(T\)
    and duration \(D\) and there are any events having a time strictly greater than
    \(T\), but strictly less than \(T + D\), then a {{NotSupportedError}} exception
    MUST be thrown.</span> In other words, it's not ok to schedule a value curve
    during a time period containing other events, but it's ok to schedule a value
    curve exactly at the time of another event.

* <span class="synchronous">Similarly a
    {{NotSupportedError}} exception MUST be thrown if any
    <a href="#dfn-automation-method">automation method</a> is called at
    a time which is contained in \([T, T+D)\), \(T\) being the time of the curve
    and \(D\) its duration.
    </span>

Note: {{AudioParam}} attributes are read only, with the exception
of the {{AudioParam/value}} attribute.

The automation rate of an {{AudioParam}} can be selected setting the
{{AudioParam/automationRate}} attribute with one of the following
values.  However, some {{AudioParam}}s have constraints on whether the
automation rate can be changed.

<pre class="idl">
enum AutomationRate {
    "a-rate",
    "k-rate"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="AutomationRate">
    <caption>{{AutomationRate}} enumeration description</caption>
    <thead>
        <tr>
            <th>Enum value</th>
            <th>Description</th>
        </tr>
    <tbody>
    <tr>
        <td>
            "<dfn>a-rate</dfn>"
        </td>
        <td>
            This {{AudioParam}} is set for [=a-rate=] processing.
        </td>
    </tr>
    <tr>
        <td>
            "<dfn>k-rate</dfn>"
        </td>
        <td>
            This {{AudioParam}} is set for [=k-rate=] processing.
        </td>
    </tr>
</table>
</div>

Each {{AudioParam}} has an internal slot <dfn attribute for=AudioParam>[[current value]]</dfn>,
initially set to the {{AudioParam}}'s {{AudioParam/defaultValue}}.

<pre class="idl">
[Exposed=Window]
interface AudioParam {
    attribute float value;
    attribute AutomationRate automationRate;
    readonly attribute float defaultValue;
    readonly attribute float minValue;
    readonly attribute float maxValue;
    AudioParam setValueAtTime (float value, double startTime);
    AudioParam linearRampToValueAtTime (float value, double endTime);
    AudioParam exponentialRampToValueAtTime (float value, double endTime);
    AudioParam setTargetAtTime (float target, double startTime, float timeConstant);
    AudioParam setValueCurveAtTime (sequence&lt;float> values,
                                    double startTime,
                                    double duration);
    AudioParam cancelScheduledValues (double cancelTime);
    AudioParam cancelAndHoldAtTime (double cancelTime);
};
</pre>

<h4 id="AudioParam-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioParam">
    : <dfn>automationRate</dfn>
    ::
        The automation rate for the {{AudioParam}}.  The
        default value depends on the actual {{AudioParam}};
        see the description of each individual {{AudioParam}} for the
        default value.

        Some nodes have additional <dfn dfn>automation rate constraints</dfn> as follows:

        : {{AudioBufferSourceNode}}
        ::
            The {{AudioParam}}s
            {{AudioBufferSourceNode/playbackRate}} and
            {{AudioBufferSourceNode/detune}} MUST be
            "{{AutomationRate/k-rate}}". <span
            class="synchronous">An {{InvalidStateError}}
            must be thrown if the rate is changed to
            "{{AutomationRate/a-rate}}"</span>.

        : {{DynamicsCompressorNode}}
        ::
            The {{AudioParam}}s
            {{DynamicsCompressorNode/threshold}},
            {{DynamicsCompressorNode/knee}},
            {{DynamicsCompressorNode/ratio}},
            {{DynamicsCompressorNode/attack}}, and
            {{DynamicsCompressorNode/release}}
            MUST be "{{AutomationRate/k-rate}}".  <span
            class="synchronous">An {{InvalidStateError}}
            must be thrown if the rate is changed to
            "{{AutomationRate/a-rate}}"</span>.

        : {{PannerNode}}
        ::
            If the {{PannerNode/panningModel}} is
            "{{PanningModelType/HRTF}}", the setting of
            the {{AudioParam/automationRate}} for any
            {{AudioParam}} of the {{PannerNode}} is ignored.
            Likewise, the setting of the
            {{AudioParam/automationRate}} for any {{AudioParam}}
            of the {{AudioListener}} is ignored.  In this
            case, the {{AudioParam}} behaves as if the
            {{AudioParam/automationRate}} were set to
            "{{AutomationRate/k-rate}}".

    : <dfn>defaultValue</dfn>
    ::
        Initial value for the <code>value</code> attribute.

    : <dfn>maxValue</dfn>
    ::
        The nominal maximum value that the parameter can take. Together
        with <code>minValue</code>, this forms the <a>nominal range</a>
        for this parameter.

    : <dfn>minValue</dfn>
    ::
        The nominal minimum value that the parameter can take. Together
        with <code>maxValue</code>, this forms the <a>nominal range</a>
        for this parameter.

    : <dfn>value</dfn>
    ::
        The parameter's floating-point value. This attribute is
        initialized to the <code>defaultValue</code>.

        Getting this attribute returns the contents of the
        {{[[current value]]}} slot. See
        [[#computation-of-value]] for the algorithm for the
        value that is returned.

        Setting this attribute has the effect of assigning the
        requested value to the {{[[current value]]}} slot, and
        calling the <a data-link-for="AudioParam">setValueAtTime()</a>
        method with the current {{AudioContext}}'s
        <code>currentTime</code> and {{[[current value]]}}. Any
        exceptions that would be thrown by
        <code>setValueAtTime()</code> will also be thrown by setting
        this attribute.
</dl>

<h4 id="AudioParam-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AudioParam">
    : <dfn>cancelAndHoldAtTime(cancelTime)</dfn>
    ::
        This is similar to {{AudioParam/cancelScheduledValues()}} in that it cancels all
        scheduled parameter changes with times greater than or equal to
        {{AudioParam/cancelAndHoldAtTime()/cancelTime!!argument}}. However, in addition, the automation
        value that would have happened at {{AudioParam/cancelAndHoldAtTime()/cancelTime!!argument}} is
        then propagated for all future time until other automation
        events are introduced.

        The behavior of the timeline in the face of
        {{AudioParam/cancelAndHoldAtTime()}} when automations are running
        and can be introduced at any time after calling
        {{AudioParam/cancelAndHoldAtTime()}} and before
        {{AudioParam/cancelAndHoldAtTime()/cancelTime!!argument}} is reached is quite complicated. The
        behavior of {{AudioParam/cancelAndHoldAtTime()}} is therefore
        specified in the following algorithm.

        <div algorithm="cancel and hold">
            Let \(t_c\) be the value of {{AudioParam/cancelAndHoldAtTime()/cancelTime!!argument}}. Then

            1. Let \(E_1\) be the event (if any) at time \(t_1\) where
                \(t_1\) is the largest number satisfying \(t_1 \le t_c\).

            2. Let \(E_2\) be the event (if any) at time \(t_2\) where
                \(t_2\) is the smallest number satisfying \(t_c \lt t_2\).

            3. If \(E_2\) exists:
                1. If \(E_2\) is a linear or exponential ramp,
                    1. Effectively rewrite \(E_2\) to be the same kind of
                        ramp ending at time \(t_c\) with an end value that
                        would be the value of the original ramp at time
                        \(t_c\).
                        <img alt="Graphical representation of calling cancelAndHoldAtTime when linearRampToValueAtTime has been called at this time." src="images/cancel-linear.svg" style="height:75%;width:75%">

                    2. Go to step 5.

                2. Otherwise, go to step 4.

            4. If \(E_1\) exists:
                1. If \(E_1\) is a <code>setTarget</code> event,
                    1. Implicitly insert a <code>setValueAtTime</code>
                        event at time \(t_c\) with the value that the
                        <code>setTarget</code> would have at time
                        \(t_c\).
                        <img alt="Graphical representation of calling cancelAndHoldAtTime when setTargetAtTime has been called at this time" src="images/cancel-setTarget.svg" style="height:75%;width:75%">

                    2. Go to step 5.

                2. If \(E_1\) is a <code>setValueCurve</code> with a start
                    time of \(t_3\) and a duration of \(d\)

                    1. If \(t_c \gt t_3 + d\), go to step 5.

                    2. Otherwise,
                        1. Effectively replace this event with a
                            <code>setValueCurve</code> event with a start time
                            of \(t_3\) and a new duration of \(t_c-t_3\).
                            However, this is not a true replacement; this
                            automation MUST take care to produce the same
                            output as the original, and not one computed using
                            a different duration. (That would cause sampling of
                            the value curve in a slightly different way,
                            producing different results.)
                            <img alt="Graphical representation of calling cancelAndHoldAtTime when setValueCurve has been called at this time" src="images/cancel-setValueCurve.svg" style="height:75%;width:75%">

                        2. Go to step 5.

            5. Remove all events with time greater than \(t_c\).

            If no events are added, then the automation value after
            {{AudioParam/cancelAndHoldAtTime()}} is the constant value that
            the original timeline would have had at time \(t_c\).
        </div>

        <pre class=argumentdef for="AudioParam/cancelAndHoldAtTime()">
            cancelTime: The time after which any previously scheduled parameter changes will be cancelled. It is a time in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute.  <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>cancelTime</code> is negative. If {{AudioParam/cancelAndHoldAtTime()/cancelTime}} is less than {{BaseAudioContext/currentTime}}, it is clamped to {{BaseAudioContext/currentTime}}.
        </pre>

        <div>
            <em>Return type:</em> {{AudioParam}}
        </div>

    : <dfn>cancelScheduledValues(cancelTime)</dfn>
    ::
        Cancels all scheduled parameter changes with times greater than
        or equal to {{AudioParam/cancelScheduledValues()/cancelTime!!argument}}. Cancelling a scheduled
        parameter change means removing the scheduled event from the
        event list. Any active automations whose <a>automation event time</a> is less
        than {{AudioParam/cancelScheduledValues()/cancelTime!!argument}} are also cancelled, and such
        cancellations may cause discontinuities because the original
        value (from before such automation) is restored immediately. Any
        hold values scheduled by {{AudioParam/cancelAndHoldAtTime()}}
        are also removed if the hold time occurs after
        {{AudioParam/cancelScheduledValues()/cancelTime!!argument}}.

        For a {{AudioParam/setValueCurveAtTime()}}, let \(T_0\) and \(T_D\) be the corresponding
        {{AudioParam/setValueCurveAtTime()/startTime!!argument}} and {{AudioParam/setValueCurveAtTime()/duration!!argument}}, respectively of this event.
        Then if {{AudioParam/cancelScheduledValues()/cancelTime!!argument}}
        is in the range \([T_0, T_0 + T_D]\), the event is
        removed from the timeline.

        <pre class=argumentdef for="AudioParam/cancelScheduledValues()">
            cancelTime: The time after which any previously scheduled parameter changes will be cancelled. It is a time in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute.  <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>cancelTime</code> is negative.</span> If <code>cancelTime</code> is less than {{BaseAudioContext/currentTime}}, it is clamped to {{BaseAudioContext/currentTime}}.
        </pre>

        <div>
            <em>Return type:</em> {{AudioParam}}
        </div>

    : <dfn>exponentialRampToValueAtTime(value, endTime)</dfn>
    ::
        Schedules an exponential continuous change in parameter value
        from the previous scheduled parameter value to the given value.
        Parameters representing filter frequencies and playback rate
        are best changed exponentially because of the way humans
        perceive sound.

        The value during the time interval \(T_0 \leq t &lt; T_1\)
        (where \(T_0\) is the time of the previous event and \(T_1\) is
        the {{AudioParam/exponentialRampToValueAtTime()/endTime!!argument}} parameter passed into this method)
        will be calculated as:

        <pre nohighlight>
        $$
            v(t) = V_0 \left(\frac{V_1}{V_0}\right)^\frac{t - T_0}{T_1 - T_0}
        $$
        </pre>

        where \(V_0\) is the value at the time \(T_0\) and \(V_1\) is
        the {{AudioParam/exponentialRampToValueAtTime()/value!!argument}} parameter passed into this method. If
        \(V_0\) and \(V_1\) have opposite signs or if \(V_0\) is zero,
        then \(v(t) = V_0\) for \(T_0 \le t \lt T_1\).

        This also implies an exponential ramp to 0 is not possible. A
        good approximation can be achieved using {{AudioParam/setTargetAtTime()}} with an appropriately chosen
        time constant.

        If there are no more events after this <em>ExponentialRampToValue</em>
        event then for \(t \geq T_1\), \(v(t) = V_1\).

        If there is no event preceding this event, the exponential ramp
        behaves as if {{AudioParam/setValueAtTime()|setValueAtTime(value, currentTime)}}
        were called where <code>value</code> is the current value of
        the attribute and <code>currentTime</code> is the context
        {{BaseAudioContext/currentTime}} at the time
        {{AudioParam/exponentialRampToValueAtTime()}} is called.

        If the preceding event is a <code>SetTarget</code> event, \(T_0\)
        and \(V_0\) are chosen from the current time and value of
        <code>SetTarget</code> automation. That is, if the
        <code>SetTarget</code> event has not started, \(T_0\) is the start
        time of the event, and \(V_0\) is the value just before the
        <code>SetTarget</code> event starts. In this case, the
        <code>ExponentialRampToValue</code> event effectively replaces the
        <code>SetTarget</code> event. If the <code>SetTarget</code> event has
        already started, \(T_0\) is the current context time, and
        \(V_0\) is the current <code>SetTarget</code> automation value at
        time \(T_0\). In both cases, the automation curve is
        continuous.

        <pre class=argumentdef for="AudioParam/exponentialRampToValueAtTime()">
            value: The value the parameter will exponentially ramp to at the given time. <span class="synchronous">A {{RangeError}} exception MUST be thrown if this value is equal to 0.</span>
            endTime: The time in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute where the exponential ramp ends. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>endTime</code> is negative or is not a finite number.</span> If <var>endTime</var> is less than {{BaseAudioContext/currentTime}}, it is clamped to {{BaseAudioContext/currentTime}}.
        </pre>

        <div>
            <em>Return type:</em> {{AudioParam}}
        </div>

    : <dfn>linearRampToValueAtTime(value, endTime)</dfn>
    ::
        Schedules a linear continuous change in parameter value from
        the previous scheduled parameter value to the given value.

        The value during the time interval \(T_0 \leq t &lt; T_1\)
        (where \(T_0\) is the time of the previous event and \(T_1\) is
        the {{AudioParam/linearRampToValueAtTime()/endTime!!argument}} parameter passed into this method)
        will be calculated as:

        <pre nohighlight>
        $$
            v(t) = V_0 + (V_1 - V_0) \frac{t - T_0}{T_1 - T_0}
        $$
        </pre>

        where \(V_0\) is the value at the time \(T_0\) and \(V_1\) is
        the {{AudioParam/linearRampToValueAtTime()/value!!argument}} parameter passed into this method.

        If there are no more events after this <em>LinearRampToValue</em> event
        then for \(t \geq T_1\), \(v(t) = V_1\).

        If there is no event preceding this event, the linear ramp
        behaves as if {{AudioParam/setValueAtTime()|setValueAtTime(value, currentTime)}}
        were called where <code>value</code> is the current value of
        the attribute and <code>currentTime</code> is the context
        {{BaseAudioContext/currentTime}} at the time
        {{AudioParam/linearRampToValueAtTime()}} is called.

        If the preceding event is a <code>SetTarget</code> event, \(T_0\)
        and \(V_0\) are chosen from the current time and value of
        <code>SetTarget</code> automation. That is, if the
        <code>SetTarget</code> event has not started, \(T_0\) is the start
        time of the event, and \(V_0\) is the value just before the
        <code>SetTarget</code> event starts. In this case, the
        <code>LinearRampToValue</code> event effectively replaces the
        <code>SetTarget</code> event. If the <code>SetTarget</code> event has
        already started, \(T_0\) is the current context time, and
        \(V_0\) is the current <code>SetTarget</code> automation value at
        time \(T_0\). In both cases, the automation curve is
        continuous.

        <pre class=argumentdef for="AudioParam/linearRampToValueAtTime()">
            value: The value the parameter will linearly ramp to at the given time.
            endTime: The time in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute at which the automation ends. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>endTime</code> is negative or is not a finite number.</span> If <var>endTime</var> is less than {{BaseAudioContext/currentTime}}, it is clamped to {{BaseAudioContext/currentTime}}.
        </pre>

        <div>
            <em>Return type:</em> {{AudioParam}}
        </div>

    : <dfn>setTargetAtTime(target, startTime, timeConstant)</dfn>
    ::
        Start exponentially approaching the target value at the given
        time with a rate having the given time constant. Among other
        uses, this is useful for implementing the "decay" and "release"
        portions of an ADSR envelope. Please note that the parameter
        value does not immediately change to the target value at the
        given time, but instead gradually changes to the target value.

        During the time interval: \(T_0 \leq t\), where \(T_0\) is the
        {{AudioParam/setTargetAtTime()/startTime!!argument}} parameter:

        <pre nohighlight>
        $$
            v(t) = V_1 + (V_0 - V_1)\, e^{-\left(\frac{t - T_0}{\tau}\right)}
        $$
        </pre>

        where \(V_0\) is the initial value (the {{[[current value]]}}
        attribute) at \(T_0\) (the {{AudioParam/setTargetAtTime()/startTime!!argument}} parameter),
        \(V_1\) is equal to the {{AudioParam/setTargetAtTime()/target!!argument}} parameter, and
        \(\tau\) is the {{AudioParam/setTargetAtTime()/timeConstant!!argument}} parameter.

        If a <code>LinearRampToValue</code> or
        <code>ExponentialRampToValue</code> event follows this event, the
        behavior is described in {{AudioParam/linearRampToValueAtTime()}} or
        {{AudioParam/exponentialRampToValueAtTime()}},
        respectively. For all other events, the <code>SetTarget</code>
        event ends at the time of the next event.

        <pre class=argumentdef for="AudioParam/setTargetAtTime()">
            target: The value the parameter will <em>start</em> changing to at the given time.
            startTime: The time at which the exponential approach will begin, in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>start</code> is negative or is not a finite number.</span> If <var>startTime</var> is less than {{BaseAudioContext/currentTime}}, it is clamped to {{BaseAudioContext/currentTime}}.
            timeConstant: The time-constant value of first-order filter (exponential) approach to the target value. The larger this value is, the slower the transition will be. <span class="synchronous">The value MUST be non-negative or a {{RangeError}} exception MUST be thrown.</span> If <code>timeConstant</code> is zero, the output value jumps immediately to the final value. More precisely, <em>timeConstant</em> is the time it takes a first-order linear continuous time-invariant system to reach the value \(1 - 1/e\) (around 63.2%) given a step input response (transition from 0 to 1 value).
        </pre>

        <div>
            <em>Return type:</em> {{AudioParam}}
        </div>

    : <dfn>setValueAtTime(value, startTime)</dfn>
    ::
        Schedules a parameter value change at the given time.

        If there are no more events after this <code>SetValue</code> event,
        then for \(t \geq T_0\), \(v(t) = V\), where \(T_0\) is the
        {{AudioParam/setValueAtTime()/startTime!!argument}} parameter and \(V\) is the
        {{AudioParam/setValueAtTime()/value!!argument}} parameter. In other words, the value will
        remain constant.

        If the next event (having time \(T_1\)) after this
        <code>SetValue</code> event is not of type
        <code>LinearRampToValue</code> or <code>ExponentialRampToValue</code>,
        then, for \(T_0 \leq t &lt; T_1\):

        <pre nohighlight>
        $$
            v(t) = V
        $$
        </pre>

        In other words, the value will remain constant during this time
        interval, allowing the creation of "step" functions.

        If the next event after this <code>SetValue</code> event is of type
        <code>LinearRampToValue</code> or <code>ExponentialRampToValue</code>
        then please see {{AudioParam/linearRampToValueAtTime()}} or
        {{AudioParam/exponentialRampToValueAtTime()}},
        respectively.

        <pre class=argumentdef for="AudioParam/setValueAtTime()">
            value: The value the parameter will change to at the given time.
            startTime: The time in the same time coordinate system as the {{BaseAudioContext}}'s {{BaseAudioContext/currentTime}} attribute at which the parameter changes to the given value. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>startTime</code> is negative or is not a finite number.</span> If <var>startTime</var> is less than {{BaseAudioContext/currentTime}}, it is clamped to {{BaseAudioContext/currentTime}}.
        </pre>

        <div>
            <em>Return type:</em> {{AudioParam}}
        </div>

    : <dfn>setValueCurveAtTime(values, startTime, duration)</dfn>
    ::
        Sets an array of arbitrary parameter values starting at the
        given time for the given duration. The number of values will be
        scaled to fit into the desired duration.

        Let \(T_0\) be {{AudioParam/setValueCurveAtTime()/startTime!!argument}}, \(T_D\) be
        {{AudioParam/setValueCurveAtTime()/duration!!argument}}, \(V\) be the {{AudioParam/setValueCurveAtTime()/values!!argument}} array,
        and \(N\) be the length of the {{AudioParam/setValueCurveAtTime()/values!!argument}} array. Then,
        during the time interval: \(T_0 \le t &lt; T_0 + T_D\), let

        <pre nohighlight>
        $$
            \begin{align*} k &amp;= \left\lfloor \frac{N - 1}{T_D}(t-T_0) \right\rfloor \\
            \end{align*}
        $$
        </pre>

        Then \(v(t)\) is computed by linearly interpolating between
        \(V[k]\) and \(V[k+1]\),

        After the end of the curve time interval (\(t \ge T_0 + T_D\)),
        the value will remain constant at the final curve value, until
        there is another automation event (if any).

        An implicit call to {{AudioParam/setValueAtTime()}} is made at time \(T_0 +
        T_D\) with value \(V\[N-1]\) so that following automations will
        start from the end of the {{AudioParam/setValueCurveAtTime()}} event.

        <pre class=argumentdef for="AudioParam/setValueCurveAtTime()">
            values: A sequence of float values representing a parameter value curve. These values will apply starting at the given time and lasting for the given duration. When this method is called, an internal copy of the curve is created for automation purposes. Subsequent modifications of the contents of the passed-in array therefore have no effect on the {{AudioParam}}. <span class="synchronous">An {{InvalidStateError}} MUST be thrown if this attribute is a <code>sequence&lt;float></code> object that has a length less than 2.</span>
            startTime: The start time in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute at which the value curve will be applied. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>startTime</code> is negative or is not a finite number</span>. If <var>startTime</var> is less than {{BaseAudioContext/currentTime}}, it is clamped to {{BaseAudioContext/currentTime}}.
            duration: The amount of time in seconds (after the <code>startTime</code> parameter) where values will be calculated according to the <code>values</code> parameter. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>duration</code> is not strictly positive or is not a finite number</span>.
        </pre>

        <div>
            <em>Return type:</em> {{AudioParam}}
        </div>
</dl>

<h4 id="computation-of-value">
Computation of Value</h4>

There are two different kind of {{AudioParam}}s, <a>simple
parameters</a> and <a>compound parameters</a>.
<dfn lt="simple parameter">Simple parameters</dfn> (the default) are used
on their own to compute the final audio output of an
{{AudioNode}}. <dfn lt="compound parameter">Compound
parameters</dfn> are {{AudioParam}}s that are used with other
{{AudioParam}}s to compute a value that is then used as an input
to compute the output of an {{AudioNode}}.

The <dfn>computedValue</dfn> is the final value controlling the audio
DSP and is computed by the audio rendering thread during each
rendering time quantum.

<div algorithm="computation-of-value">
The computation of the value of an {{AudioParam}} consists of two parts:
    - the <var>paramIntrinsicValue</var> value that is computed from the {{AudioParam/value}}
        attribute and any <a href="#dfn-automation-event">automation events</a>.
    - the <var>paramComputedValue</var> that is the final value controlling the
        audio DSP and is computed by the audio rendering thread during each
        <a>render quantum</a>.

These values MUST be computed as follows:

    1. <var>paramIntrinsicValue</var> will be calculated at
        each time, which is either the value set directly to
        the {{AudioParam/value}} attribute, or, if there are
        any <a href="#dfn-automation-event">automation
        events</a> with times before or at this time, the
        value as calculated from these events.  If automation
        events are removed from a given time range, then the
        <var>paramIntrinsicValue</var> value will remain
        unchanged and stay at its previous value until either
        the {{AudioParam/value}} attribute is directly set, or
        automation events are added for the time range.

    1. Set {{[[current value]]}} to the value of
        <var>paramIntrinsicValue</var> at the beginning of
        this <a>render quantum</a>.

    2. <var>paramComputedValue</var> is the sum of the <var>paramIntrinsicValue</var>
        value and the value of the <a href="#input-audioparam-buffer">input
        AudioParam buffer</a>.  If the sum is <code>NaN</code>, replace the sum with the {{AudioParam/defaultValue}}.

    3. If this {{AudioParam}} is a <a>compound parameter</a>,
        compute its final value with other {{AudioParam}}s.

    4. Set <a>computedValue</a> to <var>paramComputedValue</var>.
</div>

The <dfn>nominal range</dfn> for a <a>computedValue</a> are the
lower and higher values this parameter can effectively have. For
<a>simple parameters</a>, the <a>computedValue</a> is clamped to
the <a>simple nominal range</a> for this parameter. <a>Compound
parameters</a> have their final value clamped to their <a>nominal
range</a> after having been computed from the different
{{AudioParam}} values they are composed of.

When automation methods are used, clamping is still applied.
However, the automation is run as if there were no clamping at all.
Only when the automation values are to be applied to the output is
the clamping done as specified above.

<div class=example>
    For example, consider a node \(N\) has an AudioParam \(p\) with a
    nominal range of \([0, 1]\), and following automation sequence

    <pre highlight="js">
        N.p.setValueAtTime(0, 0);
        N.p.linearRampToValueAtTime(4, 1);
        N.p.linearRampToValueAtTime(0, 2);
    </pre>

    The initial slope of the curve is 4, until it reaches the maximum
    value of 1, at which time, the output is held constant. Finally,
    near time 2, the slope of the curve is -4. This is illustrated in
    the graph below where the dashed line indicates what would have
    happened without clipping, and the solid line indicates the actual
    expected behavior of the audioparam due to clipping to the nominal
    range.

    <figure>
        <!-- The image here was created from
http://googlechrome.github.io/web-audio-samples/samples/audio/timeline-limits.html -->
        <img alt="AudioParam automation clipping to nominal" src="images/audioparam-automation-clipping.png">
        <figcaption>
            An example of clipping of an AudioParam automation from the
            nominal range.
        </figcaption>
    </figure>
</div>

<h4 id="example1-AudioParam">
{{AudioParam}} Automation Example</h4>

<figure>
    <!-- The image here was created from
http://googlechrome.github.io/web-audio-samples/samples/audio/timeline.html -->
    <img alt="AudioParam automation" src="images/audioparam-automation1.png" width="917" height="541">
    <figcaption>
        An example of parameter automation.
    </figcaption>
</figure>
<pre class="example" highlight="js" line-numbers>
    const curveLength = 44100;
    const curve = new Float32Array(curveLength);
    for (const i = 0; i &lt; curveLength; ++i)
        curve[i] = Math.sin(Math.PI * i / curveLength);

    const t0 = 0;
    const t1 = 0.1;
    const t2 = 0.2;
    const t3 = 0.3;
    const t4 = 0.325;
    const t5 = 0.5;
    const t6 = 0.6;
    const t7 = 0.7;
    const t8 = 1.0;
    const timeConstant = 0.1;

    param.setValueAtTime(0.2, t0);
    param.setValueAtTime(0.3, t1);
    param.setValueAtTime(0.4, t2);
    param.linearRampToValueAtTime(1, t3);
    param.linearRampToValueAtTime(0.8, t4);
    param.setTargetAtTime(.5, t4, timeConstant);
    // Compute where the setTargetAtTime will be at time t5 so we can make
    // the following exponential start at the right point so there's no
    // jump discontinuity. From the spec, we have
    // v(t) = 0.5 + (0.8 - 0.5)*exp(-(t-t4)/timeConstant)
    // Thus v(t5) = 0.5 + (0.8 - 0.5)*exp(-(t5-t4)/timeConstant)
    param.setValueAtTime(0.5 + (0.8 - 0.5)*Math.exp(-(t5 - t4)/timeConstant), t5);
    param.exponentialRampToValueAtTime(0.75, t6);
    param.exponentialRampToValueAtTime(0.05, t7);
    param.setValueCurveAtTime(curve, t7, t8 - t7);
</pre>


<!--
   ███     ██████   ██████  ██    ██  ███████  ████████  ████████
  ██ ██   ██    ██ ██    ██ ███   ██ ██     ██ ██     ██ ██
 ██   ██  ██       ██       ████  ██ ██     ██ ██     ██ ██
██     ██  ██████   ██████  ██ ██ ██ ██     ██ ██     ██ ██████
█████████       ██       ██ ██  ████ ██     ██ ██     ██ ██
██     ██ ██    ██ ██    ██ ██   ███ ██     ██ ██     ██ ██
██     ██  ██████   ██████  ██    ██  ███████  ████████  ████████
-->

<h3 interface lt="AudioScheduledSourceNode" id="AudioScheduledSourceNode">
The {{AudioScheduledSourceNode}} Interface</h3>

The interface represents the common features of source nodes such
as {{AudioBufferSourceNode}}, {{ConstantSourceNode}}, and
{{OscillatorNode}}.

Before a source is started (by calling {{AudioScheduledSourceNode/start()}}, the source node
MUST output silence (0). After a source has been stopped (by calling
{{AudioScheduledSourceNode/stop()}}),
the source MUST then output silence (0).

{{AudioScheduledSourceNode}} cannot be instantiated directly, but
is instead extended by the concrete interfaces for the source nodes.

An {{AudioScheduledSourceNode}} is said to be <dfn>playing</dfn> when
its associated {{BaseAudioContext}}'s {{BaseAudioContext|currentTime}} is
greater or equal to the time the {{AudioScheduledSourceNode}} is set to start,
and less than the time it's set to stop.

{{AudioScheduledSourceNode}}s are created with an internal boolean
slot <dfn attribute for="AudioScheduledSourceNode">[[source started]]</dfn>, initially
set to false.

<pre class="idl">
[Exposed=Window]
interface AudioScheduledSourceNode : AudioNode {
    attribute EventHandler onended;
    undefined start(optional double when = 0);
    undefined stop(optional double when = 0);
};
</pre>

<h4 id="AudioScheduledSourceNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioScheduledSourceNode">
    : <dfn>onended</dfn>
    ::
        A property used to set an [=event handler=] for the <dfn event>ended</dfn>
        event type that is dispatched to {{AudioScheduledSourceNode}} node
        types. When the source node has stopped playing (as determined
        by the concrete node), an event that uses the {{Event}} interface will be
        dispatched to the event handler.

        For all {{AudioScheduledSourceNode}}s, the
        {{AudioScheduledSourceNode/ended}} event is dispatched when the stop time
        determined by {{AudioScheduledSourceNode/stop()}} is reached.
        For an {{AudioBufferSourceNode}}, the event is
        also dispatched because the {{AudioBufferSourceNode/start(when, offset, duration)/duration}} has been
        reached or if the entire {{AudioBufferSourceNode/buffer}} has been
        played.
</dl>

<h4 id="AudioScheduledSourceNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AudioScheduledSourceNode">
    : <dfn>start(when)</dfn>
    ::
        Schedules a sound to playback at an exact time.

        <div algorithm="AudioScheduledSourceNode.start()">
            <span class="synchronous">When this method is called, execute
            these steps:</span>

            1. <span class="synchronous">If this {{AudioScheduledSourceNode}} internal
                slot {{AudioScheduledSourceNode/[[source started]]}} is true, an
                {{InvalidStateError}} exception MUST be thrown.</span>

            2. Check for any errors that must be thrown due to parameter
                constraints described below. If any exception is thrown during this
                step, abort those steps.

            3. Set the internal slot {{AudioScheduledSourceNode/[[source started]]}} on
                this {{AudioScheduledSourceNode}} to <code>true</code>.

            4. <a>Queue a control message</a> to start the
                {{AudioScheduledSourceNode}}, including the parameter
                values in the message.

            5. Send a <a>control message</a> to the associated {{AudioContext}} to
                <a href="#context-resume">start running its rendering thread</a> only when
                all the following conditions are met:
                1. The context's {{[[control thread state]]}} is
                    "{{AudioContextState/suspended}}".
                1. The context is <a>allowed to start</a>.
                1. {{[[suspended by user]]}} flag is <code>false</code>.

                NOTE: This can allow {{AudioScheduledSourceNode/start()}} to start
                an {{AudioContext}} that is currently <a>allowed to start</a>,
                but has previously been prevented from starting.
        </div>

        <pre class=argumentdef for="AudioScheduledSourceNode/start(when)">
            when: The {{AudioScheduledSourceNode/start(when)/when}} parameter describes at what time (in seconds) the sound should start playing. It is in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute. When the signal emitted by the {{AudioScheduledSourceNode}} depends on the sound's start time, the exact value of <code>when</code> is always used without rounding to the nearest sample frame. If 0 is passed in for this value or if the value is less than {{BaseAudioContext/currentTime}}, then the sound will start playing immediately. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>when</code> is negative.</span>
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>stop(when)</dfn>
    ::
        Schedules a sound to stop playback at an exact time. If
        <code>stop</code> is called again after already having been
        called, the last invocation will be the only one applied; stop
        times set by previous calls will not be applied, unless the
        buffer has already stopped prior to any subsequent calls. If
        the buffer has already stopped, further calls to
        <code>stop</code> will have no effect. If a stop time is
        reached prior to the scheduled start time, the sound will not
        play.

        <div algorithm="AudioScheduledSourceNode.stop()">
            <span class="synchronous">When this method is called, execute these steps:</span>

            1. <span class="synchronous">If this {{AudioScheduledSourceNode}} internal
                slot {{AudioScheduledSourceNode/[[source started]]}} is not <code>true</code>,
                an {{InvalidStateError}} exception MUST be thrown.</span>

            2. Check for any errors that must be thrown due to parameter
                constraints described below.

            3. <a>Queue a control message</a> to stop the
                {{AudioScheduledSourceNode}}, including the parameter
                values in the message.
        </div>

        <div algorithm="run a control message to stop the AudioBufferSourceNode">
            If the node is an {{AudioBufferSourceNode}},
            running a <a>control message</a> to stop the
            {{AudioBufferSourceNode}} means invoking the
            <code>handleStop()</code> function in the <a href="#playback-AudioBufferSourceNode">playback algorithm</a>.
        </div>

        <pre class=argumentdef for="AudioScheduledSourceNode/stop(when)">
            when: The {{AudioScheduledSourceNode/stop(when)/when}} parameter describes at what time (in seconds) the source should stop playing. It is in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute. If 0 is passed in for this value or if the value is less than {{BaseAudioContext/currentTime}}, then the sound will stop playing immediately. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>when</code> is negative</span>.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>


<!--
   ███    ██    ██    ███    ██       ██    ██  ██████  ████████ ████████  ██    ██  ███████  ████████  ████████
  ██ ██   ███   ██   ██ ██   ██        ██  ██  ██    ██ ██       ██     ██ ███   ██ ██     ██ ██     ██ ██
 ██   ██  ████  ██  ██   ██  ██         ████   ██       ██       ██     ██ ████  ██ ██     ██ ██     ██ ██
██     ██ ██ ██ ██ ██     ██ ██          ██     ██████  ██████   ████████  ██ ██ ██ ██     ██ ██     ██ ██████
█████████ ██  ████ █████████ ██          ██          ██ ██       ██   ██   ██  ████ ██     ██ ██     ██ ██
██     ██ ██   ███ ██     ██ ██          ██    ██    ██ ██       ██    ██  ██   ███ ██     ██ ██     ██ ██
██     ██ ██    ██ ██     ██ ████████    ██     ██████  ████████ ██     ██ ██    ██  ███████  ████████  ████████
-->

<h3 interface lt="AnalyserNode" id="AnalyserNode">
The {{AnalyserNode}} Interface</h3>

This interface represents a node which is able to provide real-time
frequency and time-domain analysis information. The audio stream will
be passed un-processed from input to output.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    noo-notes: This output may be left unconnected.
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: No
</pre>

<pre class="idl">
[Exposed=Window]
interface AnalyserNode : AudioNode {
    constructor (BaseAudioContext context, optional AnalyserOptions options = {});
    undefined getFloatFrequencyData (Float32Array array);
    undefined getByteFrequencyData (Uint8Array array);
    undefined getFloatTimeDomainData (Float32Array array);
    undefined getByteTimeDomainData (Uint8Array array);
    attribute unsigned long fftSize;
    readonly attribute unsigned long frequencyBinCount;
    attribute double minDecibels;
    attribute double maxDecibels;
    attribute double smoothingTimeConstant;
};
</pre>

<h4 id="AnalyserNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="AnalyserNode">
    : <dfn>AnalyserNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="AnalyserNode/constructor()">
            context: The {{BaseAudioContext}} this new {{AnalyserNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{AnalyserNode}}.
        </pre>
</dl>

<h4 id="AnalyserNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AnalyserNode">
    : <dfn>fftSize</dfn>
    ::
        The size of the FFT used for frequency-domain analysis (in sample-frames).
        <span class="synchronous">This MUST be a power of two in the
        range 32 to 32768, otherwise an {{IndexSizeError}}
        exception MUST be thrown</span>. The default value is 2048.
        Note that large FFT sizes can be costly to compute.

        If the {{AnalyserNode/fftSize}} is changed to a different value,
        then all state associated with smoothing of the frequency data
        (for {{AnalyserNode/getByteFrequencyData()}} and
        {{AnalyserNode/getFloatFrequencyData()}}) is
        reset. That is the <a>previous block</a>, \(\hat{X}_{-1}[k]\),
        used for <a href="#smoothing-over-time">smoothing over time</a>
        is set to 0 for all \(k\).

        Note that increasing {{AnalyserNode/fftSize}} does mean that the
        <a>current time-domain data</a> must be expanded to include past
        frames that it previously did not. This means that the
        {{AnalyserNode}} effectively MUST keep around the last
        32768 sample-frames and the <a>current time-domain
        data</a> is the most recent
        {{AnalyserNode/fftSize}} sample-frames out of that.

    : <dfn>frequencyBinCount</dfn>
    ::
        Half the FFT size.

    : <dfn>maxDecibels</dfn>
    ::
        {{AnalyserNode/maxDecibels}} is the maximum power value in the scaling
        range for the FFT analysis data for conversion to unsigned byte
        values. The default value is -30. <span class="synchronous">If
        the value of this attribute is set to a value less than or equal
        to {{AnalyserNode/minDecibels}}, an
        {{IndexSizeError}} exception MUST be thrown.</span>

    : <dfn>minDecibels</dfn>
    ::
        {{AnalyserNode/minDecibels}} is the minimum power value in the scaling
        range for the FFT analysis data for conversion to unsigned byte
        values. The default value is -100. <span class="synchronous">If
        the value of this attribute is set to a value more than or equal
        to {{AnalyserNode/maxDecibels}}, an
        {{IndexSizeError}} exception MUST be thrown.</span>

    : <dfn>smoothingTimeConstant</dfn>
    ::
        A value from 0 -> 1 where 0 represents no time averaging with
        the last analysis frame. The default value is 0.8. <span class="synchronous">If the value of this attribute is set to a value
        less than 0 or more than 1, an {{IndexSizeError}}
        exception MUST be thrown.</span>
</dl>

<h4 id="AnalyserNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AnalyserNode">
    : <dfn>getByteFrequencyData(array)</dfn>
    ::
        [=ArrayBufferView/Write=] the [=current frequency data=] into |array|. If
        |array|'s [=BufferSource/byte length=] is less than {{frequencyBinCount}},
        the excess elements will be dropped. If |array|'s
        [=BufferSource/byte length=] is greater than the {{frequencyBinCount}}, the
        excess elements will be ignored. The most recent {{AnalyserNode/fftSize}}
        frames are used in computing the frequency data.

        If another call to {{AnalyserNode/getByteFrequencyData()}} or
        {{AnalyserNode/getFloatFrequencyData()}} occurs within the same
        <a>render quantum</a> as a previous call, the <a>current
        frequency data</a> is not updated with the same data. Instead,
        the previously computed data is returned.

        The values stored in the unsigned byte array are computed in
        the following way. Let \(Y[k]\) be the <a>current frequency
        data</a> as described in <a href="#fft-windowing-and-smoothing-over-time">FFT windowing and
        smoothing</a>. Then the byte value, \(b[k]\), is

        <pre nohighlight>
        $$
            b[k] = \left\lfloor
                    \frac{255}{\mbox{dB}_{max} - \mbox{dB}_{min}}
                    \left(Y[k] - \mbox{dB}_{min}\right)
                \right\rfloor
        $$
        </pre>

        where \(\mbox{dB}_{min}\) is {{AnalyserNode/minDecibels}}
        and \(\mbox{dB}_{max}\) is <code>{{AnalyserNode/maxDecibels}}</code>. If
        \(b[k]\) lies outside the range of 0 to 255, \(b[k]\) is
        clipped to lie in that range.

        <pre class=argumentdef for="AnalyserNode/getByteFrequencyData()">
            array: This parameter is where the frequency-domain analysis data will be copied.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>getByteTimeDomainData(array)</dfn>
    ::
        [=ArrayBufferView/Write=] the [=current time-domain data=] (waveform data)
        into |array|. If |array|'s [=BufferSource/byte length=] is less than
        {{AnalyserNode/fftSize}}, the excess elements will be dropped. If |array|'s
        [=BufferSource/byte length=] is greater than the {{AnalyserNode/fftSize}},
        the excess elements will be ignored. The most recent
        {{AnalyserNode/fftSize}} frames are used in computing the byte data.

        The values stored in the unsigned byte array are computed in
        the following way. Let \(x[k]\) be the time-domain data. Then
        the byte value, \(b[k]\), is

        <pre nohighlight>
        $$
            b[k] = \left\lfloor 128(1 + x[k]) \right\rfloor.
        $$
        </pre>

        If \(b[k]\) lies outside the range 0 to 255, \(b[k]\) is
        clipped to lie in that range.

        <pre class=argumentdef for="AnalyserNode/getByteTimeDomainData()">
            array: This parameter is where the time-domain sample data will be copied.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>getFloatFrequencyData(array)</dfn>
    ::
        [=ArrayBufferView/Write=] the [=current frequency data=] into |array|. If
        |array| has fewer elements than the {{frequencyBinCount}}, the excess
        elements will be dropped. If |array| has more elements than the
        {{frequencyBinCount}}, the excess elements will be ignored. The most recent
        {{AnalyserNode/fftSize}} frames are used in computing the frequency data.

        If another call to {{AnalyserNode/getFloatFrequencyData()}} or
        {{AnalyserNode/getByteFrequencyData()}} occurs within the same
        <a>render quantum</a> as a previous call, the <a>current
        frequency data</a> is not updated with the same data. Instead,
        the previously computed data is returned.

        The frequency data are in dB units.

        <pre class=argumentdef for="AnalyserNode/getFloatFrequencyData()">
            array: This parameter is where the frequency-domain analysis data will be copied.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>getFloatTimeDomainData(array)</dfn>
    ::
        [=ArrayBufferView/Write=] the [=current time-domain data=] (waveform data)
        into |array|. If |array| has fewer elements than the value of
        {{AnalyserNode/fftSize}}, the excess elements will be dropped. If |array|
        has more elements than the value of {{AnalyserNode/fftSize}}, the excess
        elements will be ignored. The most recent {{AnalyserNode/fftSize}} frames
        are written (after downmixing).

        <pre class=argumentdef for="AnalyserNode/getFloatTimeDomainData()">
            array: This parameter is where the time-domain sample data will be copied.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>

<h4 dictionary id="AnalyserOptions">
{{AnalyserOptions}}</h4>

This specifies the options to be used when constructing an
{{AnalyserNode}}. All members are optional; if not
specified, the normal default values are used to construct the
node.

<pre class="idl">
dictionary AnalyserOptions : AudioNodeOptions {
    unsigned long fftSize = 2048;
    double maxDecibels = -30;
    double minDecibels = -100;
    double smoothingTimeConstant = 0.8;
};
</pre>

<h5 id="dictionary-analyseroptions-members">
Dictionary {{AnalyserOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="AnalyserOptions">
    : <dfn>fftSize</dfn>
    :: The desired initial size of the FFT for frequency-domain analysis.

    : <dfn>maxDecibels</dfn>
    :: The desired initial maximum power in dB for FFT analysis.

    : <dfn>minDecibels</dfn>
    :: The desired initial minimum power in dB for FFT analysis.

    : <dfn>smoothingTimeConstant</dfn>
    :: The desired initial smoothing constant for the FFT analysis.
</dl>

<h4 id="time-domain-down-mixing">
Time-Domain Down-Mixing</h4>

    When the <dfn>current time-domain data</dfn> are computed, the
    input signal must be <a href="#channel-up-mixing-and-down-mixing">down-mixed</a> to mono as if
    {{AudioNode/channelCount}} is 1,
    {{AudioNode/channelCountMode}} is
    "{{ChannelCountMode/max}}" and {{AudioNode/channelInterpretation}} is "{{ChannelInterpretation/speakers}}". This is independent of the
    settings for the {{AnalyserNode}} itself. The most recent
    {{AnalyserNode/fftSize}} frames are used for the
    down-mixing operation.

<h4 id="fft-windowing-and-smoothing-over-time">
FFT Windowing and Smoothing over Time</h4>

When the <dfn id="current-frequency-data">current frequency
data</dfn> are computed, the following operations are to be
performed:

<div algorithm="compute-frequency-data">
    1. Compute the <a>current time-domain data</a>.

    2. <a href="#blackman-window">Apply a Blackman window</a> to the time domain input data.

    3. <a href="#fourier-transform">Apply a Fourier transform</a> to the
        windowed time domain input data to get real and imaginary
        frequency data.

    4. <a href="#smoothing-over-time">Smooth over time</a> the frequency domain data.

    5. <a href="#conversion-to-db">Convert to dB</a>.
</div>

In the following, let \(N\) be the value of the
{{AnalyserNode/fftSize}} attribute of this {{AnalyserNode}}.

<div algorithm="apply blackman window">
    <dfn id="blackman-window">Applying a Blackman window</dfn> consists
    in the following operation on the input time domain data. Let
    \(x[n]\) for \(n = 0, \ldots, N - 1\) be the time domain data. The
    Blackman window is defined by

    <pre nohighlight>
    $$
    \begin{align*}
        \alpha &amp;= \mbox{0.16} \\ a_0 &amp;= \frac{1-\alpha}{2} \\
        a_1 &amp;= \frac{1}{2} \\
        a_2 &amp;= \frac{\alpha}{2} \\
        w[n] &amp;= a_0 - a_1 \cos\frac{2\pi n}{N} + a_2 \cos\frac{4\pi n}{N}, \mbox{ for } n = 0, \ldots, N - 1
    \end{align*}
    $$
    </pre>

    The windowed signal \(\hat{x}[n]\) is

    <pre nohighlight>
    $$
        \hat{x}[n] = x[n] w[n], \mbox{ for } n = 0, \ldots, N - 1
    $$
    </pre>
</div>

<div algorithm="apply fourier transform">
    <dfn id="fourier-transform">Applying a Fourier transform</dfn>
    consists of computing the Fourier transform in the following way.
    Let \(X[k]\) be the complex frequency domain data and
    \(\hat{x}[n]\) be the windowed time domain data computed above.
    Then

    <pre nohighlight>
    $$
        X[k] = \frac{1}{N} \sum_{n = 0}^{N - 1} \hat{x}[n]\, W^{-kn}_{N}
    $$
    </pre>

    for \(k = 0, \dots, N/2-1\) where \(W_N = e^{2\pi i/N}\).
</div>

<div algorithm="smoothing over time">
    <dfn id="smoothing-over-time">Smoothing over time</dfn> frequency
    data consists in the following operation:

    * Let \(\hat{X}_{-1}[k]\) be the result of this operation on the
        <a>previous block</a>. The <dfn>previous block</dfn> is defined as
        being the buffer computed by the previous <a href="#smoothing-over-time">smoothing over time</a> operation, or an
        array of \(N\) zeros if this is the first time we are <a href="#smoothing-over-time">smoothing over time</a>.

    * Let \(\tau\) be the value of the {{AnalyserNode/smoothingTimeConstant}} attribute for
        this {{AnalyserNode}}.

    * Let \(X[k]\) be the result of <a href="#fourier-transform">applying a Fourier transform</a> of the current block.

    Then the smoothed value, \(\hat{X}[k]\), is computed by

    <pre nohighlight>
    $$
        \hat{X}[k] = \tau\, \hat{X}_{-1}[k] + (1 - \tau)\, \left|X[k]\right|
    $$
    </pre>

    * If \(\hat{X}[k]\) is <code>NaN</code>, positive infinity or negative infinity, set \(\hat{X}[k]\) = 0.

    for \(k = 0, \ldots, N - 1\).
</div>

<div algorithm="conversion to db">
    <dfn id="conversion-to-db">Conversion to dB</dfn> consists of the
    following operation, where \(\hat{X}[k]\) is computed in <a>smoothing over time</a>:

    <pre nohighlight>
    $$
        Y[k] = 20\log_{10}\hat{X}[k]
    $$
    </pre>

    for \(k = 0, \ldots, N-1\).

    This array, \(Y[k]\), is copied to the output array for
    {{AnalyserNode/getFloatFrequencyData()}}. For
    {{AnalyserNode/getByteFrequencyData()}}, the \(Y[k]\) is clipped to lie
    between {{AnalyserNode/minDecibels}} and
    <code>{{AnalyserNode/maxDecibels}}</code> and then scaled to fit in an
    unsigned byte such that {{AnalyserNode/minDecibels}} is
    represented by the value 0 and <code>{{AnalyserNode/maxDecibels}}</code> is
    represented by the value 255.
</div>


<!--
   ███    ████████   ██████   ███████  ██     ██ ████████   ██████  ████████ ██    ██  ███████  ████████  ████████
  ██ ██   ██     ██ ██    ██ ██     ██ ██     ██ ██     ██ ██    ██ ██       ███   ██ ██     ██ ██     ██ ██
 ██   ██  ██     ██ ██       ██     ██ ██     ██ ██     ██ ██       ██       ████  ██ ██     ██ ██     ██ ██
██     ██ ████████   ██████  ██     ██ ██     ██ ████████  ██       ██████   ██ ██ ██ ██     ██ ██     ██ ██████
█████████ ██     ██       ██ ██     ██ ██     ██ ██   ██   ██       ██       ██  ████ ██     ██ ██     ██ ██
██     ██ ██     ██ ██    ██ ██     ██ ██     ██ ██    ██  ██    ██ ██       ██   ███ ██     ██ ██     ██ ██
██     ██ ████████   ██████   ███████   ███████  ██     ██  ██████  ████████ ██    ██  ███████  ████████  ████████
-->

<h3 interface lt="AudioBufferSourceNode" id="AudioBufferSourceNode">
The {{AudioBufferSourceNode}} Interface</h3>

This interface represents an audio source from an in-memory audio
asset in an {{AudioBuffer}}. It is useful for playing audio
assets which require a high degree of scheduling flexibility and
accuracy. If sample-accurate playback of network- or disk-backed
assets is required, an implementer should use
{{AudioWorkletNode}} to implement playback.

The {{AudioScheduledSourceNode/start()}} method is used to
schedule when sound playback will happen. The {{AudioScheduledSourceNode/start()}} method may not be
issued multiple times. The playback will stop automatically when the
buffer's audio data has been completely played (if the
{{AudioBufferSourceNode/loop}}
attribute is <code>false</code>), or when the {{AudioScheduledSourceNode/stop()}} method has been
called and the specified time has been reached. Please see more
details in the {{AudioScheduledSourceNode/start()}} and
{{AudioScheduledSourceNode/stop()}}
descriptions.

<pre class=include>
path: audionode.include
macros:
    noi: 0
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: No
</pre>

The number of channels of the output equals the number of channels of the
AudioBuffer assigned to the {{AudioBufferSourceNode/buffer}} attribute,
or is one channel of silence if {{AudioBufferSourceNode/buffer}} is
<code>null</code>.

In addition, if the buffer has more than one channel,
then the {{AudioBufferSourceNode}} output must change to a single channel
of silence at the beginning of a render quantum after the time at which any one
of the following conditions holds:
    * the end of the {{AudioBufferSourceNode/buffer}} has been reached;
    * the {{AudioBufferSourceNode/start(when, offset, duration)/duration}} has been reached;
    * the {{AudioScheduledSourceNode/stop(when)/when|stop}} time has been reached.

A <dfn>playhead position</dfn> for an {{AudioBufferSourceNode}} is
defined as any quantity representing a time offset in seconds,
relative to the time coordinate of the first sample frame in the
buffer. Such values are to be considered independently from the
node's <code>playbackRate</code> and {{AudioBufferSourceNode/detune}} parameters.
In general, playhead positions may be subsample-accurate and need not
refer to exact sample frame positions. They may assume valid values
between 0 and the duration of the buffer.

The {{AudioBufferSourceNode/playbackRate}} and
{{AudioBufferSourceNode/detune}} attributes form a
<a>compound parameter</a>. They are used together to determine a
<dfn>computedPlaybackRate</dfn> value:

<pre highlight>
computedPlaybackRate(t) = playbackRate(t) * pow(2, detune(t) / 1200)
</pre>

The <a>nominal range</a> for this <a>compound parameter</a> is
\((-\infty, \infty)\).

{{AudioBufferSourceNode}}s are created with an internal boolean
slot <dfn attribute for="AudioBufferSourceNode">[[buffer set]]</dfn>, initially set to false.

<pre class="idl">
[Exposed=Window]
interface AudioBufferSourceNode : AudioScheduledSourceNode {
    constructor (BaseAudioContext context,
                 optional AudioBufferSourceOptions options = {});
    attribute AudioBuffer? buffer;
    readonly attribute AudioParam playbackRate;
    readonly attribute AudioParam detune;
    attribute boolean loop;
    attribute double loopStart;
    attribute double loopEnd;
    undefined start (optional double when = 0,
                     optional double offset,
                     optional double duration);
};
</pre>

<h4 id="AudioBufferSourceNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="AudioBufferSourceNode" id="dom-audiobuffersourcenode-constructor-audiobuffersourcenode">
    : <dfn>AudioBufferSourceNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="AudioBufferSourceNode/constructor()">
            context: The {{BaseAudioContext}} this new {{AudioBufferSourceNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{AudioBufferSourceNode}}.
        </pre>
</dl>

<h4 id="AudioBufferSourceNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioBufferSourceNode">
    : <dfn>buffer</dfn>
    ::
        Represents the audio asset to be played.

        <div algorithm="set the buffer attribute">
            To set the {{AudioBufferSourceNode/buffer}} attribute, execute these steps:

            1. Let <var>new buffer</var> be the {{AudioBuffer}} or
                <code>null</code> value to be assigned to {{AudioBufferSourceNode/buffer}}.

            2. If <var>new buffer</var> is not <code>null</code> and
                {{AudioBufferSourceNode/[[buffer set]]}} is true, throw an
                {{InvalidStateError}} and abort these steps.

            3. If <var>new buffer</var> is not <code>null</code>, set
                {{AudioBufferSourceNode/[[buffer set]]}} to true.

            4. Assign <var>new buffer</var> to the {{AudioBufferSourceNode/buffer}}
                attribute.

            5. If <code>start()</code> has previously been called on this
                node, perform the operation <a href="#acquire-the-content">acquire the content</a> on
                {{AudioBufferSourceNode/buffer}}.
        </div>

    : <dfn>detune</dfn>
    ::
        An additional parameter, in cents, to modulate the speed at
        which is rendered the audio stream. This parameter is a
        <a>compound parameter</a> with {{AudioBufferSourceNode/playbackRate}} to form a
        <a>computedPlaybackRate</a>.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/k-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>loop</dfn>
    ::
        Indicates if the region of audio data designated by
        {{AudioBufferSourceNode/loopStart}} and {{AudioBufferSourceNode/loopEnd}} should be played continuously
        in a loop. The default value is <code>false</code>.

    : <dfn>loopEnd</dfn>
    ::
        An optional <a>playhead position</a> where looping should end if
        the {{AudioBufferSourceNode/loop}} attribute is true. Its value is exclusive of the
        content of the loop. Its default <code>value</code> is 0, and it
        may usefully be set to any value between 0 and the duration of
        the buffer. If {{AudioBufferSourceNode/loopEnd}} is less than or equal to 0, or if
        {{AudioBufferSourceNode/loopEnd}} is greater than the duration of the buffer,
        looping will end at the end of the buffer.

    : <dfn>loopStart</dfn>
    ::
        An optional <a>playhead position</a> where looping should begin
        if the {{AudioBufferSourceNode/loop}} attribute is true. Its default
        <code>value</code> is 0, and it may usefully be set to any value
        between 0 and the duration of the buffer. If {{AudioBufferSourceNode/loopStart}} is
        less than 0, looping will begin at 0. If {{AudioBufferSourceNode/loopStart}} is
        greater than the duration of the buffer, looping will begin at
        the end of the buffer.

    : <dfn>playbackRate</dfn>
    ::
        The speed at which to render the audio stream. This is a
        <a>compound parameter</a> with {{AudioBufferSourceNode/detune}} to form a
        <a>computedPlaybackRate</a>.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 1
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/k-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>
</dl>

<h4 id="AudioBufferSourceNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AudioBufferSourceNode">
    : <dfn>start(when, offset, duration)</dfn>
    ::
        Schedules a sound to playback at an exact time.

        <div algorithm="AudioBufferSourceNode.start()">
            <span class="synchronous">When this method is called, execute these steps:</span>

            1. <span class="synchronous">If this {{AudioBufferSourceNode}} internal
                slot {{AudioScheduledSourceNode/[[source started]]}} is `true`, an
                {{InvalidStateError}} exception MUST be thrown.</span>

            1. Check for any errors that must be thrown due to parameter
                constraints described below.  If any
                exception is thrown during this step,
                abort those steps.

            1. Set the internal slot {{AudioScheduledSourceNode/[[source started]]}} on
                this {{AudioBufferSourceNode}} to <code>true</code>.

            1. <a>Queue a control message</a> to start the
                {{AudioBufferSourceNode}}, including the parameter values
                in the message.

            1. <a>Acquire the contents</a> of the
                {{AudioBufferSourceNode/buffer}} if the
                {{AudioBufferSourceNode/buffer}} has been set.
            1. Send a <a>control message</a> to the associated {{AudioContext}} to
                <a href="#context-resume">start running its rendering thread</a> only when
                all the following conditions are met:
                1. The context's {{[[control thread state]]}} is
                    {{AudioContextState/suspended}}.
                1. The context is <a>allowed to start</a>.
                1. {{[[suspended by user]]}} flag is <code>false</code>.

                NOTE: This can allow {{AudioBufferSourceNode/start()}} to start
                an {{AudioContext}} that is currently <a>allowed to start</a>,
                but has previously been prevented from starting.
        </div>

        <div algorithm="run a control message to start the AudioBufferSourceNode">
            Running a <a>control message</a> to start the {{AudioBufferSourceNode}}
            means invoking the <code>handleStart()</code> function in the
            [[#playback-AudioBufferSourceNode|playback algorithm]] which follows.
        </div>

        <pre class=argumentdef for="AudioBufferSourceNode/start(when, offset, duration)">
            when: The <code>when</code> parameter describes at what time (in seconds) the sound should start playing. It is in the same time coordinate system as the {{AudioContext}}'s {{BaseAudioContext/currentTime}} attribute. If 0 is passed in for this value or if the value is less than <b>currentTime</b>, then the sound will start playing immediately. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>when</code> is negative.</span>
            offset: The <code>offset</code> parameter supplies a <a>playhead position</a> where playback will begin. If 0 is passed in for this value, then playback will start from the beginning of the buffer. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>offset</code> is negative.</span> If <code>offset</code> is greater than {{AudioBufferSourceNode/loopEnd}}, {{AudioBufferSourceNode/playbackRate}} is positive or zero, and {{AudioBufferSourceNode/loop}} is <code>true</code>, playback will begin at {{AudioBufferSourceNode/loopEnd}}.  If <code>offset</code> is greater than {{AudioBufferSourceNode/loopStart}}, {{AudioBufferSourceNode/playbackRate}} is negative, and {{AudioBufferSourceNode/loop}} is <code>true</code>, playback will begin at {{AudioBufferSourceNode/loopStart}}. <code>offset</code> is silently clamped to [0, <code>duration</code>], when <code>startTime</code> is reached, where <code>duration</code> is the value of the <code>duration</code> attribute of the {{AudioBuffer}} set to the {{AudioBufferSourceNode/buffer}} attribute of this <code>AudioBufferSourceNode</code>.
            duration: The {{AudioBufferSourceNode/start(when, offset, duration)/duration}} parameter describes the duration of sound to be played, expressed as seconds of total buffer content to be output, including any whole or partial loop iterations. The units of {{AudioBufferSourceNode/start(when, offset, duration)/duration}} are independent of the effects of {{AudioBufferSourceNode/playbackRate}}. For example, a {{AudioBufferSourceNode/start(when, offset, duration)/duration}} of 5 seconds with a playback rate of 0.5 will output 5 seconds of buffer content at half speed, producing 10 seconds of audible output. <span class="synchronous">A {{RangeError}} exception MUST be thrown if <code>duration</code> is negative.</span>
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

</dl>

<h4 dictionary id="AudioBufferSourceOptions">
{{AudioBufferSourceOptions}}</h4>

This specifies options for constructing a
{{AudioBufferSourceNode}}. All members are
optional; if not specified, the normal default is used in
constructing the node.

<pre class="idl">
dictionary AudioBufferSourceOptions {
    AudioBuffer? buffer;
    float detune = 0;
    boolean loop = false;
    double loopEnd = 0;
    double loopStart = 0;
    float playbackRate = 1;
};
</pre>

<h5 id="dictionary-audiobuffersourceoptions-members">
Dictionary {{AudioBufferSourceOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="AudioBufferSourceOptions">
    : <dfn>buffer</dfn>
    ::
        The audio asset to be played. This is equivalent to assigning
        {{AudioBufferSourceOptions/buffer}} to the {{AudioBufferSourceNode/buffer}} attribute of
        the {{AudioBufferSourceNode}}.

    : <dfn>detune</dfn>
    ::
        The initial value for the {{AudioBufferSourceNode/detune}} AudioParam.

    : <dfn>loop</dfn>
    ::
        The initial value for the {{AudioBufferSourceNode/loop}} attribute.

    : <dfn>loopEnd</dfn>
    ::
        The initial value for the {{AudioBufferSourceNode/loopEnd}} attribute.

    : <dfn>loopStart</dfn>
    ::
        The initial value for the {{AudioBufferSourceNode/loopStart}} attribute.

    : <dfn>playbackRate</dfn>
    ::
        The initial value for the {{AudioBufferSourceNode/playbackRate}} AudioParam.
</dl>

<h4 id="looping-AudioBufferSourceNode">
Looping</h4>

<em>This section is non-normative. Please see <a href="#playback-AudioBufferSourceNode">the playback algorithm</a> for
normative requirements.</em>

Setting the {{AudioBufferSourceNode/loop}}
attribute to true causes playback of the region of the buffer
defined by the endpoints {{AudioBufferSourceNode/loopStart}} and {{AudioBufferSourceNode/loopEnd}} to continue indefinitely, once
any part of the looped region has been played. While
{{AudioBufferSourceNode/loop}} remains true,
looped playback will continue until one of the following occurs:

* {{AudioScheduledSourceNode/stop()}} is called,

* the scheduled stop time has been reached,

* the <code>duration</code> has been exceeded, if
    {{AudioBufferSourceNode/start()}}
    was called with a <code>duration</code> value.

The body of the loop is considered to occupy a region from
{{AudioBufferSourceNode/loopStart}} up to, but
not including, {{AudioBufferSourceNode/loopEnd}}. The direction of playback of
the looped region respects the sign of the node's playback rate.
For positive playback rates, looping occurs from {{AudioBufferSourceNode/loopStart}} to {{AudioBufferSourceNode/loopEnd}}; for negative rates, looping
occurs from {{AudioBufferSourceNode/loopEnd}} to
{{AudioBufferSourceNode/loopStart}}.

Looping does not affect the interpretation of the
<code>offset</code> argument of {{AudioBufferSourceNode/start()}}. Playback always
starts at the requested offset, and looping only begins once the
body of the loop is encountered during playback.

The effective loop start and end points are required to lie within
the range of zero and the buffer duration, as specified in the
algorithm below. {{AudioBufferSourceNode/loopEnd}} is further constrained to be at
or after {{AudioBufferSourceNode/loopStart}}. If
any of these constraints are violated, the loop is considered to
include the entire buffer contents.

Loop endpoints have subsample accuracy. When endpoints do not fall
on exact sample frame offsets, or when the playback rate is not
equal to 1, playback of the loop is interpolated to splice the
beginning and end of the loop together just as if the looped audio
occurred in sequential, non-looped regions of the buffer.

Loop-related properties may be varied during playback of the
buffer, and in general take effect on the next rendering quantum.
The exact results are defined by the normative playback algorithm
which follows.

The default values of the {{AudioBufferSourceNode/loopStart}} and {{AudioBufferSourceNode/loopEnd}} attributes are both 0. Since a
{{AudioBufferSourceNode/loopEnd}} value of zero
is equivalent to the length of the buffer, the default endpoints
cause the entire buffer to be included in the loop.

Note that the values of the loop endpoints are expressed as time
offsets in terms of the sample rate of the buffer, meaning that
these values are independent of the node's {{AudioBufferSourceNode/playbackRate}} parameter which can vary
dynamically during the course of playback.

<h4 id="playback-AudioBufferSourceNode">
Playback of AudioBuffer Contents</h4>

This normative section specifies the playback of the contents of
the buffer, accounting for the fact that playback is influenced by
the following factors working in combination:

* A starting offset, which can be expressed with sub-sample precision.

* Loop points, which can be expressed with sub-sample precision and can
     vary dynamically during playback.

* Playback rate and detuning parameters, which combine to yield a
    single <a>computedPlaybackRate</a> that can assume finite values
    which may be positive or negative.

The algorithm to be followed internally to generate output from an
{{AudioBufferSourceNode}} conforms to the following principles:

* Resampling of the buffer may be performed arbitrarily by the UA
    at any desired point to increase the efficiency or quality of the
    output.

* Sub-sample start offsets or loop points may require additional
    interpolation between sample frames.

* The playback of a looped buffer should behave identically to an
    unlooped buffer containing consecutive occurrences of the looped
    audio content, excluding any effects from interpolation.

The description of the algorithm is as follows:

<xmp highlight="js" line-numbers>
let buffer; // AudioBuffer employed by this node
let context; // AudioContext employed by this node

// The following variables capture attribute and AudioParam values for the node.
// They are updated on a k-rate basis, prior to each invocation of process().
let loop;
let detune;
let loopStart;
let loopEnd;
let playbackRate;

// Variables for the node's playback parameters
let start = 0, offset = 0, duration = Infinity; // Set by start()
let stop = Infinity; // Set by stop()


// Variables for tracking node's playback state
let bufferTime = 0, started = false, enteredLoop = false;
let bufferTimeElapsed = 0;
let dt = 1 / context.sampleRate;

// Handle invocation of start method call
function handleStart(when, pos, dur) {
    if (arguments.length >= 1) {
        start = when;
    }
    offset = pos;
    if (arguments.length >= 3) {
        duration = dur;
    }
}

// Handle invocation of stop method call
function handleStop(when) {
    if (arguments.length >= 1) {
        stop = when;
    } else {
        stop = context.currentTime;
    }
}

// Interpolate a multi-channel signal value for some sample frame.
// Returns an array of signal values.
function playbackSignal(position) {
    /*
        This function provides the playback signal function for buffer, which is a
        function that maps from a playhead position to a set of output signal
        values, one for each output channel. If |position| corresponds to the
        location of an exact sample frame in the buffer, this function returns
        that frame. Otherwise, its return value is determined by a UA-supplied
        algorithm that interpolates sample frames in the neighborhood of
        |position|.

        If |position| is greater than or equal to |loopEnd| and there is no subsequent
        sample frame in buffer, then interpolation should be based on the sequence
        of subsequent frames beginning at |loopStart|.
     */
     ...
}

// Generate a single render quantum of audio to be placed
// in the channel arrays defined by output. Returns an array
// of |numberOfFrames| sample frames to be output.
function process(numberOfFrames) {
    let currentTime = context.currentTime; // context time of next rendered frame
    const output = []; // accumulates rendered sample frames

    // Combine the two k-rate parameters affecting playback rate
    const computedPlaybackRate = playbackRate * Math.pow(2, detune / 1200);

    // Determine loop endpoints as applicable
    let actualLoopStart, actualLoopEnd;
    if (loop && buffer != null) {
        if (loopStart >= 0 && loopEnd > 0 && loopStart < loopEnd) {
            actualLoopStart = loopStart;
            actualLoopEnd = Math.min(loopEnd, buffer.duration);
        } else {
            actualLoopStart = 0;
            actualLoopEnd = buffer.duration;
        }
    } else {
        // If the loop flag is false, remove any record of the loop having been entered
        enteredLoop = false;
    }

    // Handle null buffer case
    if (buffer == null) {
        stop = currentTime; // force zero output for all time
    }

    // Render each sample frame in the quantum
    for (let index = 0; index < numberOfFrames; index++) {
        // Check that currentTime and bufferTimeElapsed are
        // within allowable range for playback
        if (currentTime < start || currentTime >= stop || bufferTimeElapsed >= duration) {
            output.push(0); // this sample frame is silent
            currentTime += dt;
            continue;
        }

        if (!started) {
            // Take note that buffer has started playing and get initial
            // playhead position.
            if (loop && computedPlaybackRate >= 0 && offset >= actualLoopEnd) {
                offset = actualLoopEnd;
            }
            if (computedPlaybackRate < 0 && loop && offset < actualLoopStart) {
                offset = actualLoopStart;
            }
            bufferTime = offset;
            started = true;
        }

        // Handle loop-related calculations
        if (loop) {
            // Determine if looped portion has been entered for the first time
            if (!enteredLoop) {
                if (offset < actualLoopEnd && bufferTime >= actualLoopStart) {
                    // playback began before or within loop, and playhead is
                    // now past loop start
                    enteredLoop = true;
                }
                if (offset >= actualLoopEnd && bufferTime < actualLoopEnd) {
                    // playback began after loop, and playhead is now prior
                    // to the loop end
                    enteredLoop = true;
                }
            }

            // Wrap loop iterations as needed. Note that enteredLoop
            // may become true inside the preceding conditional.
            if (enteredLoop) {
                while (bufferTime >= actualLoopEnd) {
                    bufferTime -= actualLoopEnd - actualLoopStart;
                }
                while (bufferTime < actualLoopStart) {
                    bufferTime += actualLoopEnd - actualLoopStart;
                }
            }
        }

        if (bufferTime >= 0 && bufferTime < buffer.duration) {
            output.push(playbackSignal(bufferTime));
        } else {
            output.push(0); // past end of buffer, so output silent frame
        }

        bufferTime += dt * computedPlaybackRate;
        bufferTimeElapsed += dt * computedPlaybackRate;
        currentTime += dt;
    } // End of render quantum loop

    if (currentTime >= stop) {
        // End playback state of this node.  No further invocations of process()
        // will occur.  Schedule a change to set the number of output channels to 1.
    }

    return output;
}
</xmp>

The following non-normative figures illustrate the behavior of the
algorithm in assorted key scenarios. Dynamic resampling of the
buffer is not considered, but as long as the times of loop
positions are not changed this does not materially affect the
resulting playback. In all figures, the following conventions
apply:

* context sample rate is 1000 Hz

* {{AudioBuffer}} content is shown with the first sample frame
    at the <em>x</em> origin.

* output signals are shown with the sample frame located at time
    <code>start</code> at the <em>x</em> origin.

* linear interpolation is depicted throughout, although a UA
    could employ other interpolation techniques.

* the <code>duration</code> values noted in the figures refer to the <code>buffer</code>, not arguments to {{AudioBufferSourceNode/start()}}

This figure illustrates basic playback of a buffer, with a simple
loop that ends after the last sample frame in the buffer:

<figure>
    <img alt="AudioBufferSourceNode basic playback" src="images/absn-basic.png" width="556" height="485">
    <figcaption>
        {{AudioBufferSourceNode}} basic playback
    </figcaption>
</figure>

This figure illustrates <code>playbackRate</code> interpolation,
showing half-speed playback of buffer contents in which every other
output sample frame is interpolated. Of particular note is the last
sample frame in the looped output, which is interpolated using the
loop start point:

<figure>
    <img alt="AudioBufferSourceNode playbackRate interpolation" src="images/absn-slow-loop.png" width="543" height="472">
    <figcaption>
        {{AudioBufferSourceNode}} playbackRate interpolation
    </figcaption>
</figure>

This figure illustrates sample rate interpolation, showing playback
of a buffer whose sample rate is 50% of the context sample rate,
resulting in a computed playback rate of 0.5 that corrects for the
difference in sample rate between the buffer and the context. The
resulting output is the same as the preceding example, but for
different reasons.

<figure>
    <img alt="AudioBufferSourceNode sample rate interpolation" src="images/absn-half-sample-rate.png" width="543" height="459">
    <figcaption>
        {{AudioBufferSourceNode}} sample rate interpolation.
    </figcaption>
</figure>

This figure illustrates subsample offset playback, in which the
offset within the buffer begins at exactly half a sample frame.
Consequently, every output frame is interpolated:

<figure>
    <img alt="AudioBufferSourceNode subsample offset playback" src="images/absn-offset.png" width="543" height="448">
    <figcaption>
        {{AudioBufferSourceNode}} subsample offset playback
    </figcaption>
</figure>

This figure illustrates subsample loop playback, showing how
fractional frame offsets in the loop endpoints map to interpolated
data points in the buffer that respect these offsets as if they
were references to exact sample frames:

<figure>
    <img alt="AudioBufferSourceNode subsample loop playback" src="images/absn-subsample-loop.png" width="543" height="480">
    <figcaption>
        {{AudioBufferSourceNode}} subsample loop playback
    </figcaption>
</figure>


<!--
████████  ████████  ██████  ████████ ████ ██    ██    ███    ████████ ████  ███████  ██    ██
██     ██ ██       ██    ██    ██     ██  ███   ██   ██ ██      ██     ██  ██     ██ ███   ██
██     ██ ██       ██          ██     ██  ████  ██  ██   ██     ██     ██  ██     ██ ████  ██
██     ██ ██████    ██████     ██     ██  ██ ██ ██ ██     ██    ██     ██  ██     ██ ██ ██ ██
██     ██ ██             ██    ██     ██  ██  ████ █████████    ██     ██  ██     ██ ██  ████
██     ██ ██       ██    ██    ██     ██  ██   ███ ██     ██    ██     ██  ██     ██ ██   ███
████████  ████████  ██████     ██    ████ ██    ██ ██     ██    ██    ████  ███████  ██    ██
-->

<h3 interface lt="AudioDestinationNode" id="AudioDestinationNode">
The {{AudioDestinationNode}} Interface</h3>

This is an {{AudioNode}} representing the final audio
destination and is what the user will ultimately hear. It can often
be considered as an audio output device which is connected to
speakers. All rendered audio to be heard will be routed to this node,
a "terminal" node in the {{AudioContext}}'s routing
graph. There is only a single AudioDestinationNode per
{{AudioContext}}, provided through the
<code>destination</code> attribute of
{{AudioContext}}.

The output of a {{AudioDestinationNode}} is produced
by <a href="#channel-up-mixing-and-down-mixing">summing its input</a>, allowing to
capture the output of an {{AudioContext}} into, for
example, a {{MediaStreamAudioDestinationNode}}, or a
<code>MediaRecorder</code> (described in [[mediastream-recording]]).

The {{AudioDestinationNode}} can be either the destination of an
{{AudioContext}} or {{OfflineAudioContext}}, and the channel
properties depend on what the context is.

For an {{AudioContext}}, the defaults are

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-mode: explicit
    cc-interp: speakers
    tail-time: No
</pre>

The {{AudioNode/channelCount}} can be set to any
value less than or equal to {{AudioDestinationNode/maxChannelCount}}. <span class="synchronous">An {{IndexSizeError}} exception MUST be thrown
if this value is not within the valid range.</span> Giving a concrete
example, if the audio hardware supports 8-channel output, then we may
set {{AudioNode/channelCount}} to 8, and render 8
channels of output.

For an {{OfflineAudioContext}}, the defaults are

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: numberOfChannels
    cc-mode: explicit
    cc-interp: speakers
    tail-time: No
</pre>

where <code>numberOfChannels</code> is the number of channels
specified when constructing the {{OfflineAudioContext}}. This
value may not be changed; <span class="synchronous">a
{{NotSupportedError}} exception MUST be thrown if
{{AudioNode/channelCount}} is changed to a
different value</span>.

<pre class="idl">
[Exposed=Window]
interface AudioDestinationNode : AudioNode {
    readonly attribute unsigned long maxChannelCount;
};
</pre>

<h4 id="AudioDestinationNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioDestinationNode">
    : <dfn>maxChannelCount</dfn>
    ::
        The maximum number of channels that the {{AudioNode/channelCount}} attribute can be set
        to. An {{AudioDestinationNode}} representing the
        audio hardware end-point (the normal case) can potentially output
        more than 2 channels of audio if the audio hardware is
        multi-channel. {{AudioDestinationNode/maxChannelCount}} is the maximum number
        of channels that this hardware is capable of supporting.
</dl>


<!--
██       ████  ██████  ████████ ████████ ██    ██ ████████ ████████
██        ██  ██    ██    ██    ██       ███   ██ ██       ██     ██
██        ██  ██          ██    ██       ████  ██ ██       ██     ██
██        ██   ██████     ██    ██████   ██ ██ ██ ██████   ████████
██        ██        ██    ██    ██       ██  ████ ██       ██   ██
██        ██  ██    ██    ██    ██       ██   ███ ██       ██    ██
████████ ████  ██████     ██    ████████ ██    ██ ████████ ██     ██
-->

<h3 interface lt="AudioListener" id="AudioListener">
The {{AudioListener}} Interface</h3>

This interface represents the position and orientation of the person
listening to the audio scene. All {{PannerNode}}
objects spatialize in relation to the
{{BaseAudioContext}}'s {{BaseAudioContext/listener}}. See [[#Spatialization]]
for more details about spatialization.

The {{AudioListener/positionX}}, {{AudioListener/positionY}}, and {{AudioListener/positionZ}} parameters represent
the location of the listener in 3D Cartesian coordinate space.
{{PannerNode}} objects use this position relative to
individual audio sources for spatialization.

The {{AudioListener/forwardX}}, {{AudioListener/forwardY}}, and {{AudioListener/forwardZ}} parameters represent a
direction vector in 3D space. Both a <code>forward</code> vector and
an <code>up</code> vector are used to determine the orientation of
the listener. In simple human terms, the <code>forward</code> vector
represents which direction the person's nose is pointing. The
<code>up</code> vector represents the direction the top of a person's
head is pointing. These two vectors are expected to be linearly
independent. For normative requirements of how these values are to be
interpreted, see the [[#Spatialization]] section.

<pre class="idl">
[Exposed=Window]
interface AudioListener {
    readonly attribute AudioParam positionX;
    readonly attribute AudioParam positionY;
    readonly attribute AudioParam positionZ;
    readonly attribute AudioParam forwardX;
    readonly attribute AudioParam forwardY;
    readonly attribute AudioParam forwardZ;
    readonly attribute AudioParam upX;
    readonly attribute AudioParam upY;
    readonly attribute AudioParam upZ;
    undefined setPosition (float x, float y, float z);
    undefined setOrientation (float x, float y, float z, float xUp, float yUp, float zUp);
};
</pre>

<h4 id="AudioListener-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioListener">
    : <dfn>forwardX</dfn>
    ::
        Sets the x coordinate component of the forward direction the
        listener is pointing in 3D Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>forwardY</dfn>
    ::
        Sets the y coordinate component of the forward direction the
        listener is pointing in 3D Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>forwardZ</dfn>
    ::
        Sets the z coordinate component of the forward direction the
        listener is pointing in 3D Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: -1
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>positionX</dfn>
    ::
        Sets the x coordinate position of the audio listener in a 3D
        Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>positionY</dfn>
    ::
        Sets the y coordinate position of the audio listener in a 3D
        Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>positionZ</dfn>
    ::
        Sets the z coordinate position of the audio listener in a 3D
        Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>upX</dfn>
    ::
        Sets the x coordinate component of the up direction the
        listener is pointing in 3D Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>upY</dfn>
    ::
        Sets the y coordinate component of the up direction the
        listener is pointing in 3D Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 1
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>upZ</dfn>
    ::
        Sets the z coordinate component of the up direction the
        listener is pointing in 3D Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>
</dl>

<h4 id="AudioListener-methods">
Methods</h4>

<dl dfn-type=method dfn-for="AudioListener">
    : <dfn>setOrientation(x, y, z, xUp, yUp, zUp)</dfn>
    ::
        This method is DEPRECATED. It is equivalent to setting
        {{forwardX}}.{{AudioParam/value}},
        {{forwardY}}.{{AudioParam/value}},
        {{forwardZ}}.{{AudioParam/value}},
        {{upX}}.{{AudioParam/value}},
        {{upY}}.{{AudioParam/value}}, and
        {{upZ}}.{{AudioParam/value}} directly
        with the given <code>x</code>, <code>y</code>, <code>z</code>,
        <code>xUp</code>, <code>yUp</code>, and <code>zUp</code>
        values, respectively.

        <span class="synchronous">Consequently, if any of the {{forwardX}}, {{forwardY}},
        {{forwardZ}}, {{upX}}, {{upY}} and {{upZ}}
        {{AudioParam}}s have an automation curve set using
        {{AudioParam/setValueCurveAtTime()}} at the time
        this method is called, a {{NotSupportedError}} MUST be
        thrown.</span>

        {{AudioListener/setOrientation()}} describes which direction the listener is pointing in the 3D
        cartesian coordinate space. Both a [=forward=] vector and an
        [=up=] vector are provided. In simple human terms, the
        <dfn dfn>forward</dfn> vector represents which direction the person's
        nose is pointing. The <dfn dfn>up</dfn> vector represents the direction
        the top of a person's head is pointing. These two vectors are
        expected to be linearly independent. For normative requirements
        of how these values are to be interpreted, see the [[#Spatialization]].

        The {{AudioListener/setOrientation()/x!!argument}}, {{AudioListener/setOrientation()/y!!argument}}, and {{AudioListener/setOrientation()/z!!argument}} parameters represent a <a>forward</a>
        direction vector in 3D space, with the default value being
        (0,0,-1).

        The {{AudioListener/setOrientation()/xUp!!argument}}, {{AudioListener/setOrientation()/yUp!!argument}}, and {{AudioListener/setOrientation()/zUp!!argument}} parameters represent an
        <a>up</a> direction vector in 3D space, with the default value
        being (0,1,0).

        <pre class=argumentdef for="AudioListener/setOrientation()">
            x: forward <em>x</em> direction fo the {{AudioListener}}
            y: forward <em>y</em> direction fo the {{AudioListener}}
            z: forward <em>z</em> direction fo the {{AudioListener}}
            xUp: up <em>x</em> direction fo the {{AudioListener}}
            yUp: up <em>y</em> direction fo the {{AudioListener}}
            zUp: up <em>z</em> direction fo the {{AudioListener}}
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>setPosition(x, y, z)</dfn>
    ::
        This method is DEPRECATED. It is equivalent to setting
        {{AudioListener/positionX}}.{{AudioParam/value}},
        {{AudioListener/positionY}}.{{AudioParam/value}}, and
        {{AudioListener/positionZ}}.{{AudioParam/value}}
        directly with the given <code>x</code>, <code>y</code>, and
        <code>z</code> values, respectively.

        <span class="synchronous">Consequently, any of the {{AudioListener/positionX}}, {{AudioListener/positionY}},
        and {{AudioListener/positionZ}} {{AudioParam}}s for this
        {{AudioListener}} have an automation curve set using
        {{AudioParam/setValueCurveAtTime()}} at the time
        this method is called, a {{NotSupportedError}} MUST be
        thrown.</span>

        {{AudioListener/setPosition()}} sets the position of the listener in a 3D cartesian coordinate
        space. {{PannerNode}} objects use this position
        relative to individual audio sources for spatialization.

        The {{AudioListener/setPosition()/x!!argument}}, {{AudioListener/setPosition()/y!!argument}}, and {{AudioListener/setPosition()/z!!argument}} parameters represent the coordinates
        in 3D space.

        The default value is (0,0,0).

        <pre class=argumentdef for="AudioListener/setPosition()">
            x: <em>x</em>-coordinate of the position of the {{AudioListener}}
            y: <em>y</em>-coordinate of the position of the {{AudioListener}}
            z: <em>z</em>-coordinate of the position of the {{AudioListener}}
        </pre>
</dl>

<h4 id="listenerprocessing">
Processing</h4>

Because {{AudioListener}}'s parameters can be connected with {{AudioNode}}s and
they can also affect the output of {{PannerNode}}s in the same graph, the node
ordering algorithm should take the {{AudioListener}} into consideration when
computing the order of processing. For this reason, all the {{PannerNode}}s in
the graph have the {{AudioListener}} as input.

<!--
████████  ████████   ███████   ██████  ████████  ██████   ██████  ████ ██    ██  ██████
██     ██ ██     ██ ██     ██ ██    ██ ██       ██    ██ ██    ██  ██  ███   ██ ██    ██
██     ██ ██     ██ ██     ██ ██       ██       ██       ██        ██  ████  ██ ██
████████  ████████  ██     ██ ██       ██████    ██████   ██████   ██  ██ ██ ██ ██   ████
██        ██   ██   ██     ██ ██       ██             ██       ██  ██  ██  ████ ██    ██
██        ██    ██  ██     ██ ██    ██ ██       ██    ██ ██    ██  ██  ██   ███ ██    ██
██        ██     ██  ███████   ██████  ████████  ██████   ██████  ████ ██    ██  ██████
-->

<h3 interface lt="AudioProcessingEvent" id="AudioProcessingEvent">
The {{AudioProcessingEvent}} Interface - DEPRECATED</h3>

This is an {{Event}} object which is dispatched to
{{ScriptProcessorNode}} nodes. It will be removed
when the ScriptProcessorNode is removed, as the replacement
{{AudioWorkletNode}} uses a different approach.

The event handler processes audio from the input (if any) by
accessing the audio data from the <code>inputBuffer</code> attribute.
The audio data which is the result of the processing (or the
synthesized data if there are no inputs) is then placed into the
{{AudioProcessingEvent/outputBuffer}}.

<pre class="idl">
[Exposed=Window]
interface AudioProcessingEvent : Event {
    constructor (DOMString type, AudioProcessingEventInit eventInitDict);
    readonly attribute double playbackTime;
    readonly attribute AudioBuffer inputBuffer;
    readonly attribute AudioBuffer outputBuffer;
};
</pre>

<h4 id="AudioProcessingEvent-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioProcessingEvent">
    : <dfn>inputBuffer</dfn>
    ::
        An AudioBuffer containing the input audio data. It will have a
        number of channels equal to the
        <code>numberOfInputChannels</code> parameter of the
        createScriptProcessor() method. This AudioBuffer is only valid
        while in the scope of the {{ScriptProcessorNode/audioprocess}} event handler functions.
        Its values will be meaningless outside of this scope.

    : <dfn>outputBuffer</dfn>
    ::
        An AudioBuffer where the output audio data MUST be written. It
        will have a number of channels equal to the
        <code>numberOfOutputChannels</code> parameter of the
        createScriptProcessor() method. Script code within the scope of
        the {{ScriptProcessorNode/audioprocess}} event handler functions are
        expected to modify the {{Float32Array}} arrays
        representing channel data in this AudioBuffer. Any script
        modifications to this AudioBuffer outside of this scope will not
        produce any audible effects.

    : <dfn>playbackTime</dfn>
    ::
        The time when the audio will be played in the same time
        coordinate system as the {{AudioContext}}'s
        {{BaseAudioContext/currentTime}}.
</dl>

<h4 dictionary id="AudioProcessingEventInit">
{{AudioProcessingEventInit}}</h4>

<pre class="idl">
dictionary AudioProcessingEventInit : EventInit {
    required double playbackTime;
    required AudioBuffer inputBuffer;
    required AudioBuffer outputBuffer;
};
</pre>

<h5 id="dictionary-audioprocessingeventinit-members">
Dictionary {{AudioProcessingEventInit}} Members</h5>

<dl dfn-type=dict-member dfn-for="AudioProcessingEventInit">
    : <dfn>inputBuffer</dfn>
    ::
        Value to be assigned to the {{AudioProcessingEvent/inputBuffer}} attribute
        of the event.

    : <dfn>outputBuffer</dfn>
    ::
        Value to be assigned to the {{AudioProcessingEvent/outputBuffer}} attribute
        of the event.

    : <dfn>playbackTime</dfn>
    ::
        Value to be assigned to the {{AudioProcessingEvent/playbackTime}} attribute
        of the event.
</dl>

<h3 interface lt="BiquadFilterNode" id="BiquadFilterNode">
The {{BiquadFilterNode}} Interface</h3>

{{BiquadFilterNode}} is an
{{AudioNode}} processor implementing very common
low-order filters.

Low-order filters are the building blocks of basic tone controls
(bass, mid, treble), graphic equalizers, and more advanced filters.
Multiple {{BiquadFilterNode}} filters can be combined
to form more complex filters. The filter parameters such as
{{BiquadFilterNode/frequency}} can be
changed over time for filter sweeps, etc. Each
{{BiquadFilterNode}} can be configured as one of a
number of common filter types as shown in the IDL below. The default
filter type is <code>"lowpass"</code>.

Both {{BiquadFilterNode/frequency}}
and {{BiquadFilterNode/detune}} form
a <a>compound parameter</a> and are both <a>a-rate</a>. They are used
together to determine a <dfn>computedFrequency</dfn> value:

<pre highlight>
    computedFrequency(t) = frequency(t) * pow(2, detune(t) / 1200)
</pre>

The <a>nominal range</a> for this <a>compound parameter</a> is [0,
<a>Nyquist frequency</a>].


<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: Yes
    tail-time-notes:  Continues to output non-silent audio with zero input. Since this is an IIR filter, the filter produces non-zero input forever, but in practice, this can be limited after some finite time where the output is sufficiently close to zero. The actual time depends on the filter coefficients.
</pre>

The number of channels of the output always equals the number of
channels of the input.

<pre class="idl">
enum BiquadFilterType {
    "lowpass",
    "highpass",
    "bandpass",
    "lowshelf",
    "highshelf",
    "peaking",
    "notch",
    "allpass"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="BiquadFilterType">
    <caption>{{BiquadFilterType}} enumeration description</caption>
    <thead>
    <tr>
        <th>Enum value</th><th>Description</th>
    <tbody>
    <tr>
        <td>"<dfn>lowpass</dfn>"
        <td>
            A <a href="https://en.wikipedia.org/wiki/Low-pass_filter">lowpass
            filter</a> allows frequencies below the cutoff frequency to
            pass through and attenuates frequencies above the cutoff. It
            implements a standard second-order resonant lowpass filter with
            12dB/octave rolloff.

            : frequency
            :: The cutoff frequency
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Controls how peaked the response will be at the cutoff
                frequency. A large value makes the response more peaked.
            : gain
            :: Not used in this filter type
    <tr>
        <td>"<dfn>highpass</dfn>"
        <td>
            A <a href="https://en.wikipedia.org/wiki/High-pass_filter">highpass
            filter</a> is the opposite of a lowpass filter. Frequencies
            above the cutoff frequency are passed through, but frequencies
            below the cutoff are attenuated. It implements a standard
            second-order resonant highpass filter with 12dB/octave rolloff.

            : frequency
            :: The cutoff frequency below which the frequencies are
                attenuated
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Controls how peaked the response will be at the cutoff
                frequency. A large value makes the response more peaked.
            : gain
            :: Not used in this filter type
    <tr>
        <td>"<dfn>bandpass</dfn>"
        <td>
            A <a href="https://en.wikipedia.org/wiki/Band-pass_filter">bandpass
            filter</a> allows a range of frequencies to pass through and
            attenuates the frequencies below and above this frequency
            range. It implements a second-order bandpass filter.

            : frequency
            :: The center of the frequency band
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Controls the width of the band. The width becomes narrower
                as the Q value increases.
            : gain
            :: Not used in this filter type
    <tr>
        <td>"<dfn>lowshelf</dfn>"
        <td>
            The lowshelf filter allows all frequencies through, but adds a
            boost (or attenuation) to the lower frequencies. It implements
            a second-order lowshelf filter.

            : frequency
            :: The upper limit of the frequences where the boost (or
                attenuation) is applied.
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Not used in this filter type.
            : gain
            :: The boost, in dB, to be applied. If the value is negative,
                the frequencies are attenuated.
    <tr>
        <td>"<dfn>highshelf</dfn>"
        <td>
            The highshelf filter is the opposite of the lowshelf filter and
            allows all frequencies through, but adds a boost to the higher
            frequencies. It implements a second-order highshelf filter

            : frequency
            :: The lower limit of the frequences where the boost (or
                attenuation) is applied.
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Not used in this filter type.
            : gain
            :: The boost, in dB, to be applied. If the value is negative,
                the frequencies are attenuated.
    <tr>
        <td>"<dfn>peaking</dfn>"
        <td>
            The peaking filter allows all frequencies through, but adds a
            boost (or attenuation) to a range of frequencies.

            : frequency
            :: The center frequency of where the boost is applied.
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Controls the width of the band of frequencies that are
                boosted. A large value implies a narrow width.
            : gain
            :: The boost, in dB, to be applied. If the value is negative,
                the frequencies are attenuated.
    <tr>
        <td>"<dfn>notch</dfn>"
        <td>
            The notch filter (also known as a <a href="https://en.wikipedia.org/wiki/Band-stop_filter">band-stop or
            band-rejection filter</a>) is the opposite of a bandpass
            filter. It allows all frequencies through, except for a set of
            frequencies.

            : frequency
            :: The center frequency of where the notch is applied.
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Controls the width of the band of frequencies that are
                attenuated. A large value implies a narrow width.
            : gain
            :: Not used in this filter type.
    <tr>
        <td>"<dfn>allpass</dfn>"
        <td>
            An <a href="https://en.wikipedia.org/wiki/All-pass_filter#Digital_implementation">
            allpass filter</a> allows all frequencies through, but changes
            the phase relationship between the various frequencies. It
            implements a second-order allpass filter

            : frequency
            :: The frequency where the center of the phase transition
                occurs. Viewed another way, this is the frequency with
                maximal <a href="https://en.wikipedia.org/wiki/Group_delay">group
                delay</a>.
            : <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
            :: Controls how sharp the phase transition is at the center
                frequency. A larger value implies a sharper transition and
                a larger group delay.
            : gain
            :: Not used in this filter type.
</table>
</div>

All attributes of the {{BiquadFilterNode}} are <a>a-rate</a> {{AudioParam}}s.

<pre class="idl">
[Exposed=Window]
interface BiquadFilterNode : AudioNode {
    constructor (BaseAudioContext context, optional BiquadFilterOptions options = {});
    attribute BiquadFilterType type;
    readonly attribute AudioParam frequency;
    readonly attribute AudioParam detune;
    readonly attribute AudioParam Q;
    readonly attribute AudioParam gain;
    undefined getFrequencyResponse (Float32Array frequencyHz,
                                    Float32Array magResponse,
                                    Float32Array phaseResponse);
};
</pre>

<h4 id="BiquadFilterNode-constructors">
Constructors</h4>

<dl dfn-type=method dfn-for="BiquadFilterNode">
    : <dfn>BiquadFilterNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="BiquadFilterNode/constructor()">
            context: The {{BaseAudioContext}} this new {{BiquadFilterNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{BiquadFilterNode}}.
        </pre>
</dl>

<h4 id="BiquadFilterNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="BiquadFilterNode">
    : <dfn>Q</dfn>
    ::
        The <a href="https://en.wikipedia.org/wiki/Q_factor">Q</a>
        factor of the filter.

        For {{BiquadFilterType/lowpass}} and
        {{BiquadFilterType/highpass}} filters the
        {{BiquadFilterNode/Q}} value is interpreted to be in
        dB.  For these filters the nominal range is
        \([-Q_{lim}, Q_{lim}]\) where \(Q_{lim}\) is the largest
        value for which \(10^{Q/20}\) does not overflow.  This
        is approximately \(770.63678\).

        For the {{BiquadFilterType/bandpass}},
        {{BiquadFilterType/notch}},
        {{BiquadFilterType/allpass}}, and
        {{BiquadFilterType/peaking}} filters, this value is a
        linear value.  The value is related to the bandwidth
        of the filter and hence should be a positive value.
        The nominal range is \([0, 3.4028235e38]\), the upper
        limit being the <a>most-positive-single-float</a>.

        This is not used for the {{BiquadFilterType/lowshelf}}
        and {{BiquadFilterType/highshelf}} filters.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 1
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38, but see above for the actual limits for different filters
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38, but see above for the actual limits for different filters
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>detune</dfn>
    ::
        A detune value, in cents, for the frequency. It forms a
        <a>compound parameter</a> with {{BiquadFilterNode/frequency}} to form the <a>computedFrequency</a>.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: \(\approx -153600\)
            min-notes:
            max: \(\approx 153600\)
            max-notes: This value is approximately \(1200\ \log_2 \mathrm{FLT\_MAX}\) where FLT_MAX is the largest {{float}} value.
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>frequency</dfn>
    ::
        The frequency at which the {{BiquadFilterNode}}
        will operate, in Hz. It forms a <a>compound parameter</a> with
        {{BiquadFilterNode/detune}} to form the <a>computedFrequency</a>.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 350
            min: 0
            max: <a>Nyquist frequency</a>
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>gain</dfn>
    ::
        The gain of the filter. Its value is in dB units. The gain is
        only used for {{BiquadFilterType/lowshelf}},
        {{BiquadFilterType/highshelf}}, and
        {{BiquadFilterType/peaking}} filters.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: \(\approx 1541\)
            max-notes: This value is approximately \(40\ \log_{10} \mathrm{FLT\_MAX}\) where FLT_MAX is the largest {{float}} value.
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>type</dfn>
    ::
        The type of this {{BiquadFilterNode}}. Its
        default value is "{{BiquadFilterType/lowpass}}". The exact meaning of the other
        parameters depend on the value of the {{BiquadFilterNode/type}}
        attribute.
</dl>

<h4 id="BiquadFilterNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="BiquadFilterNode">
    : <dfn>getFrequencyResponse(frequencyHz, magResponse, phaseResponse)</dfn>
    ::
        <span class="synchronous">Given the {{[[current value]]}}
        from each of the filter parameters, synchronously
        calculates the frequency response for
        the specified frequencies. The three parameters MUST be
        {{Float32Array}}s of the same length, or an
        {{InvalidAccessError}} MUST be thrown.</span>

        The frequency response returned MUST be computed with the
        {{AudioParam}} sampled for the current
        processing block.

        <pre class=argumentdef for="BiquadFilterNode/getFrequencyResponse()">
            frequencyHz: This parameter specifies an array of frequencies, in Hz, at which the response values will be calculated.
            magResponse: This parameter specifies an output array receiving the linear magnitude response values. If a value in the <code>frequencyHz</code> parameter is not within [0, sampleRate/2], where <code>sampleRate</code> is the value of the {{BaseAudioContext/sampleRate}} property of the {{AudioContext}}, the corresponding value at the same index of the <code>magResponse</code> array MUST be <code>NaN</code>.
            phaseResponse: This parameter specifies an output array receiving the phase response values in radians. If a value in the <code>frequencyHz</code> parameter is not within [0; sampleRate/2], where <code>sampleRate</code> is the value of the {{BaseAudioContext/sampleRate}} property of the {{AudioContext}}, the corresponding value at the same index of the <code>phaseResponse</code> array MUST be <code>NaN</code>.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>

<h4 dictionary lt="BiquadFilterOptions" id="BiquadFilterOptions">
{{BiquadFilterOptions}}</h4>

This specifies the options to be used when constructing a
{{BiquadFilterNode}}. All members are optional; if
not specified, the normal default values are used to construct the
node.

<pre class="idl">
dictionary BiquadFilterOptions : AudioNodeOptions {
    BiquadFilterType type = "lowpass";
    float Q = 1;
    float detune = 0;
    float frequency = 350;
    float gain = 0;
};
</pre>

<h5 id="dictionary-biquadfilteroptions-members">
Dictionary {{BiquadFilterOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="BiquadFilterOptions">
    : <dfn>Q</dfn>
    :: The desired initial value for {{BiquadFilterNode/Q}}.

    : <dfn>detune</dfn>
    :: The desired initial value for {{BiquadFilterNode/detune}}.

    : <dfn>frequency</dfn>
    :: The desired initial value for {{BiquadFilterNode/frequency}}.

    : <dfn>gain</dfn>
    :: The desired initial value for {{BiquadFilterNode/gain}}.

    : <dfn>type</dfn>
    :: The desired initial type of the filter.
</dl>

<h4 id="filters-characteristics">
Filters Characteristics</h4>

There are multiple ways of implementing the type of filters
available through the {{BiquadFilterNode}} each
having very different characteristics. The formulas in this section
describe the filters that a <a>conforming implementation</a> MUST
implement, as they determine the characteristics of the different
filter types. They are inspired by formulas found in the
<a href="https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html">Audio EQ Cookbook</a>.

The {{BiquadFilterNode}} processes audio with a transfer function of

<pre nohighlight>
$$
 H(z) = \frac{\frac{b_0}{a_0} + \frac{b_1}{a_0}z^{-1} + \frac{b_2}{a_0}z^{-2}}
                                          {1+\frac{a_1}{a_0}z^{-1}+\frac{a_2}{a_0}z^{-2}}
$$
</pre>

which is equivalent to a time-domain equation of:

<pre nohighlight>
$$
a_0 y(n) + a_1 y(n-1) + a_2 y(n-2) =
    b_0 x(n) + b_1 x(n-1) + b_2 x(n-2)
$$
</pre>


The initial filter state is 0.

Note: While fixed filters are stable, it is possible to create
unstable biquad filters using automations of {{AudioParam}}s.  It is
the developers responsibility to manage this.

Note: The UA may produce a warning to notify the user that NaN values have occurred in the filter state.  This is usually indicative of an unstable filter.

The coefficients in the transfer function above are different for
each node type. The following intermediate variables are necessary for
their computation, based on the <a>computedValue</a> of the
{{AudioParam}}s of the
{{BiquadFilterNode}}.

* Let \(F_s\) be the value of the {{BaseAudioContext/sampleRate}} attribute for this {{AudioContext}}.

* Let \(f_0\) be the value of the <a>computedFrequency</a>.

* Let \(G\) be the value of the {{BiquadFilterNode/gain}} {{AudioParam}}.

* Let \(Q\) be the value of the {{BiquadFilterNode/Q}} {{AudioParam}}.

* Finally let
    <!-- Should \alpha_S be simplified since S is always 1?-->
    <pre nohighlight>
    $$
    \begin{align*}
        A &amp;= 10^{\frac{G}{40}} \\
        \omega_0 &amp;= 2\pi\frac{f_0}{F_s} \\
        \alpha_Q &amp;= \frac{\sin\omega_0}{2Q} \\
        \alpha_{Q_{dB}} &amp;= \frac{\sin\omega_0}{2 \cdot 10^{Q/20}} \\
        S &amp;= 1 \\
        \alpha_S &amp;= \frac{\sin\omega_0}{2}\sqrt{\left(A+\frac{1}{A}\right)\left(\frac{1}{S}-1\right)+2}
    \end{align*}
    $$
    </pre>

The six coefficients (\(b_0, b_1, b_2, a_0, a_1, a_2\)) for each
filter type, are:

: "{{lowpass}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= \frac{1 - \cos\omega_0}{2} \\
            b_1 &amp;= 1 - \cos\omega_0 \\
            b_2 &amp;= \frac{1 - \cos\omega_0}{2} \\
            a_0 &amp;= 1 + \alpha_{Q_{dB}} \\
            a_1 &amp;= -2 \cos\omega_0 \\
            a_2 &amp;= 1 - \alpha_{Q_{dB}}
        \end{align*}
    $$
    </pre>

: "{{highpass}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= \frac{1 + \cos\omega_0}{2} \\
            b_1 &amp;= -(1 + \cos\omega_0) \\
            b_2 &amp;= \frac{1 + \cos\omega_0}{2} \\
            a_0 &amp;= 1 + \alpha_{Q_{dB}} \\
            a_1 &amp;= -2 \cos\omega_0 \\
            a_2 &amp;= 1 - \alpha_{Q_{dB}}
        \end{align*}
    $$
    </pre>

: "{{bandpass}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= \alpha_Q \\
            b_1 &amp;= 0 \\
            b_2 &amp;= -\alpha_Q \\
            a_0 &amp;= 1 + \alpha_Q \\
            a_1 &amp;= -2 \cos\omega_0 \\
            a_2 &amp;= 1 - \alpha_Q
        \end{align*}
    $$
    </pre>

: "{{notch}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= 1 \\
            b_1 &amp;= -2\cos\omega_0 \\
            b_2 &amp;= 1 \\
            a_0 &amp;= 1 + \alpha_Q \\
            a_1 &amp;= -2 \cos\omega_0 \\
            a_2 &amp;= 1 - \alpha_Q
        \end{align*}
    $$
    </pre>

: "{{allpass}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= 1 - \alpha_Q \\
            b_1 &amp;= -2\cos\omega_0 \\
            b_2 &amp;= 1 + \alpha_Q \\
            a_0 &amp;= 1 + \alpha_Q \\
            a_1 &amp;= -2 \cos\omega_0 \\
            a_2 &amp;= 1 - \alpha_Q
        \end{align*}
    $$
    </pre>

: "{{peaking}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= 1 + \alpha_Q\, A \\
            b_1 &amp;= -2\cos\omega_0 \\
            b_2 &amp;= 1 - \alpha_Q\,A \\
            a_0 &amp;= 1 + \frac{\alpha_Q}{A} \\
            a_1 &amp;= -2 \cos\omega_0 \\
            a_2 &amp;= 1 - \frac{\alpha_Q}{A}
        \end{align*}
    $$
    </pre>

: "{{lowshelf}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= A \left[ (A+1) - (A-1) \cos\omega_0 + 2 \alpha_S \sqrt{A})\right] \\
            b_1 &amp;= 2 A \left[ (A-1) - (A+1) \cos\omega_0 )\right] \\
            b_2 &amp;= A \left[ (A+1) - (A-1) \cos\omega_0 - 2 \alpha_S \sqrt{A}) \right] \\
            a_0 &amp;= (A+1) + (A-1) \cos\omega_0 + 2 \alpha_S \sqrt{A} \\
            a_1 &amp;= -2 \left[ (A-1) + (A+1) \cos\omega_0\right] \\
            a_2 &amp;= (A+1) + (A-1) \cos\omega_0 - 2 \alpha_S \sqrt{A})
        \end{align*}
    $$
    </pre>

: "{{highshelf}}"
::
    <pre nohighlight>
    $$
        \begin{align*}
            b_0 &amp;= A\left[ (A+1) + (A-1)\cos\omega_0 + 2\alpha_S\sqrt{A} )\right] \\
            b_1 &amp;= -2A\left[ (A-1) + (A+1)\cos\omega_0 )\right] \\
            b_2 &amp;= A\left[ (A+1) + (A-1)\cos\omega_0 - 2\alpha_S\sqrt{A} )\right] \\
            a_0 &amp;= (A+1) - (A-1)\cos\omega_0 + 2\alpha_S\sqrt{A} \\
            a_1 &amp;= 2\left[ (A-1) - (A+1)\cos\omega_0\right] \\
            a_2 &amp;= (A+1) - (A-1)\cos\omega_0 - 2\alpha_S\sqrt{A}
        \end{align*}
    $$
    </pre>


<!--
 ██████  ██     ██    ███    ██    ██ ██    ██ ████████ ██
██    ██ ██     ██   ██ ██   ███   ██ ███   ██ ██       ██
██       ██     ██  ██   ██  ████  ██ ████  ██ ██       ██
██       █████████ ██     ██ ██ ██ ██ ██ ██ ██ ██████   ██
██       ██     ██ █████████ ██  ████ ██  ████ ██       ██
██    ██ ██     ██ ██     ██ ██   ███ ██   ███ ██       ██
 ██████  ██     ██ ██     ██ ██    ██ ██    ██ ████████ ████████

██     ██ ████████ ████████   ██████   ████████ ████████
███   ███ ██       ██     ██ ██    ██  ██       ██     ██
████ ████ ██       ██     ██ ██        ██       ██     ██
██ ███ ██ ██████   ████████  ██   ████ ██████   ████████
██     ██ ██       ██   ██   ██    ██  ██       ██   ██
██     ██ ██       ██    ██  ██    ██  ██       ██    ██
██     ██ ████████ ██     ██  ██████   ████████ ██     ██
-->

<h3 interface lt="ChannelMergerNode" id="ChannelMergerNode">
The {{ChannelMergerNode}} Interface</h3>

The {{ChannelMergerNode}} is for use in more advanced
applications and would often be used in conjunction with
{{ChannelSplitterNode}}.

<pre class=include>
path: audionode.include
macros:
    noi: see notes
    noi-notes:  Defaults to 6, but is determined by {{ChannelMergerOptions}},{{ChannelMergerOptions/numberOfInputs}} or the value specified by {{BaseAudioContext/createChannelMerger}}.
    noo: 1
    cc: 1
    cc-notes: Has <a>channelCount constraints</a>
    cc-mode: explicit
    cc-mode-notes: Has <a>channelCountMode constraints</a>
    cc-interp: speakers
    tail-time: No
</pre>

This interface represents an {{AudioNode}} for
combining channels from multiple audio streams into a single audio
stream. It has a variable number of inputs (defaulting to 6), but not
all of them need be connected. There is a single output whose audio
stream has a number of channels equal to the number of inputs when any
of the inputs is [=actively processing=].  If none of the inputs are
[=actively processing=], then output is a single channel of silence.

To merge multiple inputs into one stream, each input gets downmixed
into one channel (mono) based on the specified mixing rule. An
unconnected input still counts as <b>one silent channel</b> in the
output. Changing input streams does <b>not</b> affect the order of
output channels.

<div class=example>
    For example, if a default {{ChannelMergerNode}} has
    two connected stereo inputs, the first and second input will be
    downmixed to mono respectively before merging. The output will be a
    6-channel stream whose first two channels are be filled with the
    first two (downmixed) inputs and the rest of channels will be silent.

    Also the {{ChannelMergerNode}} can be used to arrange
    multiple audio streams in a certain order for the multi-channel
    speaker array such as 5.1 surround set up. The merger does not
    interpret the channel identities (such as left, right, etc.), but
    simply combines channels in the order that they are input.

    <figure>
        <img alt="channel merger" src="images/channel-merger.svg">
        <figcaption>
            A diagram of ChannelMerger
        </figcaption>
    </figure>
</div>

<pre class="idl">
[Exposed=Window]
interface ChannelMergerNode : AudioNode {
    constructor (BaseAudioContext context, optional ChannelMergerOptions options = {});
};
</pre>

<h4 id="ChannelMergerNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="ChannelMergerNode" id="dom-channelmergernode-constructor-channelmergernode">
    : <dfn>ChannelMergerNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="ChannelMergerNode/constructor()">
            context: The {{BaseAudioContext}} this new {{ChannelMergerNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{ChannelMergerNode}}.
        </pre>
</dl>

<h4 dictionary id="ChannelMergerOptions">
{{ChannelMergerOptions}}</h4>

<pre class="idl">
dictionary ChannelMergerOptions : AudioNodeOptions {
    unsigned long numberOfInputs = 6;
};
</pre>

<h5 id="dictionary-channelmergeroptions-members">
Dictionary {{ChannelMergerOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="ChannelMergerOptions">
    : <dfn>numberOfInputs</dfn>
    :: The number inputs for the {{ChannelMergerNode}}.  See {{BaseAudioContext/createChannelMerger()}} for constraints on this value.
</dl>


<!--
 ██████  ██     ██    ███    ██    ██ ██    ██ ████████ ██
██    ██ ██     ██   ██ ██   ███   ██ ███   ██ ██       ██
██       ██     ██  ██   ██  ████  ██ ████  ██ ██       ██
██       █████████ ██     ██ ██ ██ ██ ██ ██ ██ ██████   ██
██       ██     ██ █████████ ██  ████ ██  ████ ██       ██
██    ██ ██     ██ ██     ██ ██   ███ ██   ███ ██       ██
 ██████  ██     ██ ██     ██ ██    ██ ██    ██ ████████ ████████

 ██████  ████████  ██       ████ ████████ ████████ ████████ ████████
██    ██ ██     ██ ██        ██     ██       ██    ██       ██     ██
██       ██     ██ ██        ██     ██       ██    ██       ██     ██
 ██████  ████████  ██        ██     ██       ██    ██████   ████████
      ██ ██        ██        ██     ██       ██    ██       ██   ██
██    ██ ██        ██        ██     ██       ██    ██       ██    ██
 ██████  ██        ████████ ████    ██       ██    ████████ ██     ██
-->

<h3 interface lt="ChannelSplitterNode" id="ChannelSplitterNode">
The {{ChannelSplitterNode}} Interface</h3>

The {{ChannelSplitterNode}} is for use in more advanced
applications and would often be used in conjunction with
{{ChannelMergerNode}}.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: see notes
    noo-notes:  This defaults to 6, but is otherwise determined from {{ChannelSplitterOptions/numberOfOutputs|ChannelSplitterOptions.numberOfOutputs}} or the value specified by {{BaseAudioContext/createChannelSplitter}} or the {{ChannelSplitterOptions/numberOfOutputs}} member of the {{ChannelSplitterOptions}} dictionary for the {{ChannelSplitterNode/ChannelSplitterNode()|constructor}}.
    cc: {{AudioNode/numberOfOutputs}}
    cc-notes: Has <a>channelCount constraints</a>
    cc-mode: explicit
    cc-mode-notes: Has <a>channelCountMode constraints</a>
    cc-interp: discrete
    cc-interp-notes: Has <a>channelInterpretation constraints</a>
    tail-time: No
</pre>

This interface represents an {{AudioNode}} for
accessing the individual channels of an audio stream in the routing
graph. It has a single input, and a number of "active" outputs which
equals the number of channels in the input audio stream. For example,
if a stereo input is connected to an
{{ChannelSplitterNode}} then the number of active
outputs will be two (one from the left channel and one from the
right). There are always a total number of N outputs (determined by
the <code>numberOfOutputs</code> parameter to the
{{AudioContext}} method {{BaseAudioContext/createChannelSplitter()}}), The
default number is 6 if this value is not provided. Any outputs which
are not "active" will output silence and would typically not be
connected to anything.

<div class=example>
    <figure>
        <img alt="channel splitter" src="images/channel-splitter.png" width="601" height="398">
        <figcaption>
            A diagram of a ChannelSplitter
        </figcaption>
    </figure>

    Please note that in this example, the splitter does <b>not</b>
    interpret the channel identities (such as left, right, etc.), but
    simply splits out channels in the order that they are input.
</div>

One application for {{ChannelSplitterNode}} is for doing
"matrix mixing" where individual gain control of each channel is
desired.

<pre class="idl">
[Exposed=Window]
interface ChannelSplitterNode : AudioNode {
    constructor (BaseAudioContext context, optional ChannelSplitterOptions options = {});
};
</pre>

<h4 id="ChannelSplitterNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="ChannelSplitterNode" id="dom-channelsplitternode-constructor-channelsplitternode">
    : <dfn>ChannelSplitterNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="ChannelSplitterNode/constructor()">
            context: The {{BaseAudioContext}} this new {{ChannelSplitterNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{ChannelSplitterNode}}.
        </pre>
</dl>

<h4 dictionary id="ChannelSplitterOptions">
{{ChannelSplitterOptions}}</h4>

<pre class="idl">
dictionary ChannelSplitterOptions : AudioNodeOptions {
    unsigned long numberOfOutputs = 6;
};
</pre>

<h5 id="dictionary-channelsplitteroptions-members">
Dictionary {{ChannelSplitterOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="ChannelSplitterOptions">
    : <dfn>numberOfOutputs</dfn>
    :: The number outputs for the {{ChannelSplitterNode}}.  See {{BaseAudioContext/createChannelSplitter()}} for constraints on this value.
</dl>


<!--
 ██████   ███████  ██    ██  ██████  ████████    ███    ██    ██ ████████
██    ██ ██     ██ ███   ██ ██    ██    ██      ██ ██   ███   ██    ██
██       ██     ██ ████  ██ ██          ██     ██   ██  ████  ██    ██
██       ██     ██ ██ ██ ██  ██████     ██    ██     ██ ██ ██ ██    ██
██       ██     ██ ██  ████       ██    ██    █████████ ██  ████    ██
██    ██ ██     ██ ██   ███ ██    ██    ██    ██     ██ ██   ███    ██
 ██████   ███████  ██    ██  ██████     ██    ██     ██ ██    ██    ██

 ██████   ███████  ██     ██ ████████   ██████  ████████
██    ██ ██     ██ ██     ██ ██     ██ ██    ██ ██
██       ██     ██ ██     ██ ██     ██ ██       ██
 ██████  ██     ██ ██     ██ ████████  ██       ██████
      ██ ██     ██ ██     ██ ██   ██   ██       ██
██    ██ ██     ██ ██     ██ ██    ██  ██    ██ ██
 ██████   ███████   ███████  ██     ██  ██████  ████████
-->

<h3 interface lt="ConstantSourceNode" id="ConstantSourceNode">
The {{ConstantSourceNode}} Interface</h3>

This interface represents a constant audio source whose output is
nominally a constant value. It is useful as a constant source node in
general and can be used as if it were a constructible
{{AudioParam}} by automating its
{{ConstantSourceNode/offset}} or connecting another node to it.

The single output of this node consists of one channel (mono).

<pre class=include>
path: audionode.include
macros:
    noi: 0
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: No
</pre>

<pre class="idl">
[Exposed=Window]
interface ConstantSourceNode : AudioScheduledSourceNode {
    constructor (BaseAudioContext context, optional ConstantSourceOptions options = {});
    readonly attribute AudioParam offset;
};
</pre>

<h4 id="ConstantSourceNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="ConstantSourceNode" id="dom-constantsourcenode-constructor-constantsourcenode">
    : <dfn>ConstantSourceNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="ConstantSourceNode/constructor()">
            context: The {{BaseAudioContext}} this new {{ConstantSourceNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{ConstantSourceNode}}.
        </pre>
</dl>

<h4 id="ConstantSourceNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="ConstantSourceNode">
    : <dfn>offset</dfn>
    ::
        The constant value of the source.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 1
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>
</dl>

<h4 dictionary id="ConstantSourceOptions">
{{ConstantSourceOptions}}</h4>

This specifies options for constructing a
{{ConstantSourceNode}}. All members are optional;
if not specified, the normal defaults are used for constructing the
node.

<pre class="idl">
dictionary ConstantSourceOptions {
    float offset = 1;
};
</pre>

<h5 id="dictionary-constantsourceoptions-members">
Dictionary {{ConstantSourceOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="ConstantSourceOptions">
    : <dfn>offset</dfn>
    :: The initial value for the {{ConstantSourceNode/offset}} AudioParam of this node.
</dl>


<!--
 ██████   ███████  ██    ██ ██     ██  ███████  ██       ██     ██ ████████ ████████
██    ██ ██     ██ ███   ██ ██     ██ ██     ██ ██       ██     ██ ██       ██     ██
██       ██     ██ ████  ██ ██     ██ ██     ██ ██       ██     ██ ██       ██     ██
██       ██     ██ ██ ██ ██ ██     ██ ██     ██ ██       ██     ██ ██████   ████████
██       ██     ██ ██  ████  ██   ██  ██     ██ ██        ██   ██  ██       ██   ██
██    ██ ██     ██ ██   ███   ██ ██   ██     ██ ██         ██ ██   ██       ██    ██
 ██████   ███████  ██    ██    ███     ███████  ████████    ███    ████████ ██     ██
-->

<h3 interface lt="ConvolverNode" id="ConvolverNode">
The {{ConvolverNode}} Interface</h3>

This interface represents a processing node which applies a linear
convolution effect given an impulse response.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-notes: Has <a>channelCount constraints</a>
    cc-mode: clamped-max
    cc-mode-notes: Has <a>channelCountMode constraints</a>
    cc-interp: speakers
    tail-time: Yes
    tail-time-notes: Continues to output non-silent audio with zero input for the length of the {{ConvolverNode/buffer}}.
</pre>

The input of this node is either mono (1 channel) or stereo (2
channels) and cannot be increased. Connections from nodes with more
channels will be <a href="#channel-up-mixing-and-down-mixing">down-mixed appropriately</a>.

There are <a>channelCount constraints</a> and <a>channelCountMode
constraints</a> for this node. These constraints ensure that the
input to the node is either mono or stereo.

<pre class="idl">
[Exposed=Window]
interface ConvolverNode : AudioNode {
    constructor (BaseAudioContext context, optional ConvolverOptions options = {});
    attribute AudioBuffer? buffer;
    attribute boolean normalize;
};
</pre>

<h4 id="ConvolverNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="ConvolverNode" id="dom-convolvernode-constructor-convolvernode">
    : <dfn>ConvolverNode(context, options)</dfn>
    ::
        When the constructor is called with a {{BaseAudioContext}} <var>context</var> and
        an option object <var>options</var>, execute these steps:

        1. Set the attributes {{ConvolverNode/normalize}} to the inverse of the
            value of {{ConvolverOptions/disableNormalization}}.
        2. If {{ConvolverNode/buffer}}
                <a for=map>exists</a>, set the
            {{ConvolverNode/buffer}} attribute to its value.

            Note: This means that the buffer will be normalized according to the
            value of the {{ConvolverNode/normalize}}
            attribute.

        3. Let <var>o</var> be new {{AudioNodeOptions}} dictionary.
        4. If {{AudioNodeOptions/channelCount}}
                <a for=map>exists</a> in
            <var>options</var>, set {{AudioNodeOptions/channelCount}} on <var>o</var>
            with the same value.
        5. If {{AudioNodeOptions/channelCountMode}} 
            <a for=map>exists</a> in
            <var>options</var>, set {{AudioNodeOptions/channelCountMode}} on
            <var>o</var> with the same value.
        6. If {{AudioNodeOptions/channelInterpretation}} 
            <a for=map>exists</a> in
            <var>options</var>, set {{AudioNodeOptions/channelInterpretation}} on
            <var>o</var> with the same value.
        7. <a href="#audionode-constructor-init">Initialize the AudioNode</a>
            <var>this</var>, with <var>c</var> and <var>o</var> as argument.

        <pre class=argumentdef for="ConvolverNode/constructor()">
            context: The {{BaseAudioContext}} this new {{ConvolverNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{ConvolverNode}}.
        </pre>
</dl>

<h4 id="ConvolverNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="ConvolverNode">
    : <dfn>buffer</dfn>
    ::
        At the time when this attribute is set, the {{ConvolverNode/buffer}} and
        the state of the {{normalize}} attribute will be used to
        configure the {{ConvolverNode}} with this
        impulse response having the given normalization. The initial
        value of this attribute is null.

        <div algorithm="set convolver buffer">
            When setting the <dfn>buffer attribute</dfn>, execute the following <span
                class="synchronously">steps synchronously</span>:
            1. If the buffer {{AudioBuffer/numberOfChannels|number of channels}} is not 1, 2, 4, or if the
                {{AudioBuffer/sampleRate|sample-rate}} of the buffer is not the same as the
                {{BaseAudioContext/sampleRate|sample-rate}} of its <a
                    href="#associated">associated</a> {{BaseAudioContext}}, a
                {{NotSupportedError}} MUST be thrown.
            2. <a href="#acquire-the-content">Acquire the content</a> of the
                {{AudioBuffer}}.
        </div>

        Note: If the {{ConvolverNode/buffer}} is set to an new
        buffer, audio may glitch.  If this is undesirable, it
        is recommended to create a new {{ConvolverNode}} to
        replace the old, possibly cross-fading between the
        two.

        Note: The {{ConvolverNode}} produces a mono output only in the
        single case where there is a single input channel and a
        single-channel {{ConvolverNode/buffer}}. In all other cases, the
        output is stereo. In particular, when the {{ConvolverNode/buffer}}
        has four channels and there are two input channels, the
        {{ConvolverNode}} performs matrix "true" stereo
        convolution. For normative information please see the
        <a href="#Convolution-channel-configurations">channel
        configuration diagrams</a>

    : <dfn>normalize</dfn>
    ::
        Controls whether the impulse response from the buffer will be
        scaled by an equal-power normalization when the
        {{ConvolverNode/buffer}} attribute is set. Its default value is
        `true` in order to achieve a more uniform output
        level from the convolver when loaded with diverse impulse
        responses. If {{normalize}} is set to
        <code>false</code>, then the convolution will be rendered with
        no pre-processing/scaling of the impulse response. Changes to
        this value do not take effect until the next time the
        {{ConvolverNode/buffer}} attribute is set.

        If the {{normalize}} attribute is false when the
        {{ConvolverNode/buffer}} attribute is set then the
        {{ConvolverNode}} will perform a linear
        convolution given the exact impulse response contained within
        the {{ConvolverNode/buffer}}.

        Otherwise, if the {{normalize}} attribute is true when the
        {{ConvolverNode/buffer}} attribute is set then the
        {{ConvolverNode}} will first perform a scaled
        RMS-power analysis of the audio data contained within
        {{ConvolverNode/buffer}} to calculate a <var>normalizationScale</var>
        given this algorithm:

        <pre highlight="js" line-numbers>
        function calculateNormalizationScale(buffer) {
            const GainCalibration = 0.00125;
            const GainCalibrationSampleRate = 44100;
            const MinPower = 0.000125;

            // Normalize by RMS power.
            const numberOfChannels = buffer.numberOfChannels;
            const length = buffer.length;

            let power = 0;

            for (let i = 0; i &lt; numberOfChannels; i++) {
                let channelPower = 0;
                const channelData = buffer.getChannelData(i);

                for (let j = 0; j &lt; length; j++) {
                    const sample = channelData[j];
                    channelPower += sample * sample;
                }

                power += channelPower;
            }

            power = Math.sqrt(power / (numberOfChannels * length));

            // Protect against accidental overload.
            if (!isFinite(power) || isNaN(power) || power &lt; MinPower)
                power = MinPower;

            let scale = 1 / power;

            // Calibrate to make perceived volume same as unprocessed.
            scale *= GainCalibration;

            // Scale depends on sample-rate.
            if (buffer.sampleRate)
                scale *= GainCalibrationSampleRate / buffer.sampleRate;

            // True-stereo compensation.
            if (numberOfChannels == 4)
                scale *= 0.5;

            return scale;
        }
        </pre>

        During processing, the ConvolverNode will then take this
        calculated <var>normalizationScale</var> value and multiply it by
        the result of the linear convolution resulting from processing
        the input with the impulse response (represented by the
        {{ConvolverNode/buffer}}) to produce the final output. Or any
        mathematically equivalent operation may be used, such as
        pre-multiplying the input by <var>normalizationScale</var>, or
        pre-multiplying a version of the impulse-response by
        <var>normalizationScale</var>.
</dl>

<h4 dictionary id="ConvolverOptions">
{{ConvolverOptions}}</h4>

The specifies options for constructing a
{{ConvolverNode}}. All members are optional; if not
specified, the node is contructing using the normal defaults.

<pre class="idl">
dictionary ConvolverOptions : AudioNodeOptions {
    AudioBuffer? buffer;
    boolean disableNormalization = false;
};
</pre>

<h5 id="dictionary-convolveroptions-members">
Dictionary {{ConvolverOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="ConvolverOptions">
    : <dfn>buffer</dfn>
    ::
        The desired buffer for the {{ConvolverNode}}.
        This buffer will be normalized according to the value of
        {{ConvolverOptions/disableNormalization}}.

    : <dfn>disableNormalization</dfn>
    ::
        The opposite of the desired initial value for the
        {{ConvolverNode/normalize}}
        attribute of the {{ConvolverNode}}.
</dl>

<h4 id="Convolution-channel-configurations">
Channel Configurations for Input, Impulse Response and Output</h4>

Implementations MUST support the following allowable configurations
of impulse response channels in a {{ConvolverNode}}
to achieve various reverb effects with 1 or 2 channels of input.

As shown in the diagram below, single channel convolution operates on a mono audio input, using a
mono impulse response, and generating a mono output. The remaining
images in the diagram illustrate the supported cases for mono and
stereo playback where the number of channels of the input is 1 or 2, and the number of channels in the {{ConvolverNode/buffer}} is 1, 2, or 4.
Developers desiring more complex and arbitrary matrixing can use a
{{ChannelSplitterNode}}, multiple single-channel
{{ConvolverNode}}s and a
{{ChannelMergerNode}}.

If this node is not [=actively processing=], the output is a single
channel of silence.

Note: The diagrams below show the outputs when [=actively processing=].

<figure id="convolver-diagram">
    <img alt="reverb matrixing" src="images/convolver-diagram.png">
    <figcaption>
        A graphical representation of supported input and output channel
        count possibilities when using a
        {{ConvolverNode}}.
    </figcaption>
</figure>


<!--
████████  ████████ ██          ███    ██    ██
██     ██ ██       ██         ██ ██    ██  ██
██     ██ ██       ██        ██   ██    ████
██     ██ ██████   ██       ██     ██    ██
██     ██ ██       ██       █████████    ██
██     ██ ██       ██       ██     ██    ██
████████  ████████ ████████ ██     ██    ██
-->

<h3 interface lt="DelayNode" id="DelayNode">
The {{DelayNode}} Interface</h3>

A delay-line is a fundamental building block in audio applications.
This interface is an {{AudioNode}} with a single
input and single output.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: Yes
    tail-time-notes: Continues to output non-silent audio with zero input up to the <l>{{DelayOptions/maxDelayTime}}</l> of the node.
</pre>

The number of channels of the output always equals the number of
channels of the input.

It delays the incoming audio signal by a certain amount.
Specifically, at each time <em>t</em>, input signal
<em>input(t)</em>, delay time <em>delayTime(t)</em> and output signal
<em>output(t)</em>, the output will be <em>output(t) = input(t -
delayTime(t))</em>. The default <code>delayTime</code> is 0 seconds
(no delay).

When the number of channels in a {{DelayNode}}'s input changes
(thus changing the output channel count also), there may be delayed
audio samples which have not yet been output by the node and are part
of its internal state. If these samples were received earlier with a
different channel count, they MUST be upmixed or downmixed before
being combined with newly received input so that all internal
delay-line mixing takes place using the single prevailing channel
layout.

Note: By definition, a {{DelayNode}} introduces an audio processing
latency equal to the amount of the delay.

<pre class="idl">
[Exposed=Window]
interface DelayNode : AudioNode {
    constructor (BaseAudioContext context, optional DelayOptions options = {});
    readonly attribute AudioParam delayTime;
};
</pre>

<h4 id="DelayNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="DelayNode" id="dom-delaynode-constructor-delaynode">
    : <dfn>DelayNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="DelayNode/constructor()">
            context: The {{BaseAudioContext}} this new {{DelayNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{DelayNode}}.
        </pre>
</dl>

<h4 id="DelayNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="DelayNode">
    : <dfn>delayTime</dfn>
    ::
        An {{AudioParam}} object representing the
        amount of delay (in seconds) to apply. Its default
        <code>value</code> is 0 (no delay). The minimum value is 0 and
        the maximum value is determined by the
        {{maxDelayTime!!argument}} argument to the
        {{AudioContext}} method {{createDelay()}} or the {{DelayOptions/maxDelayTime}} member of the {{DelayOptions}} dictionary for the {{DelayNode/DelayNode()|constructor}}.

        If {{DelayNode}} is part of a <a>cycle</a>,
        then the value of the {{DelayNode/delayTime}} attribute
        is clamped to a minimum of one <a>render quantum</a>.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: 0
            max: <l>{{DelayOptions/maxDelayTime}}</l>
            rate: "{{AutomationRate/a-rate}}"
        </pre>
</dl>

<h4 dictionary id="DelayOptions">
{{DelayOptions}}</h4>

This specifies options for constructing a
{{DelayNode}}. All members are optional; if not
given, the node is constructed using the normal defaults.

<pre class="idl">
dictionary DelayOptions : AudioNodeOptions {
    double maxDelayTime = 1;
    double delayTime = 0;
};
</pre>

<h5 id="dictionary-delayoptions-members">
Dictionary {{DelayOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="DelayOptions">
    : <dfn>delayTime</dfn>
    :: The initial delay time for the node.

    : <dfn>maxDelayTime</dfn>
    :: The maximum delay time for the node.  See {{BaseAudioContext/createDelay(maxDelayTime)/maxDelayTime!!argument|createDelay(maxDelayTime)}} for constraints.
</dl>

<h4 id="DelayNode-processing">Processing</h4>

A {{DelayNode}} has an internal buffer that holds {{DelayNode|delayTime}}
seconds of audio.

The processing of a {{DelayNode}} is broken down in two parts: writing to the
delay line, and reading from the delay line. This is done via two internal
{{AudioNode}}s (that are not available to authors and exist only to ease
the description of the inner workings of the node). Both are created from a
{{DelayNode}}.

Creating a <dfn>DelayWriter</dfn> for a {{DelayNode}} means creating an object
that has the same interface as an {{AudioNode}}, and that writes the input audio
into the internal buffer of the {{DelayNode}}. It has the same input connections
as the {{DelayNode}} it was created from.

Creating a <dfn>DelayReader</dfn> for a {{DelayNode}} means creating an object
that has the same interface as an {{AudioNode}}, and that can read the audio
data from the internal buffer of the {{DelayNode}}. It is connected to the same
{{AudioNode}}s as the {{DelayNode}} it was created from. A <a>DelayReader</a> is
a <a>source node</a>.

When processing an input buffer, a <a>DelayWriter</a> MUST write the audio to
the internal buffer of the {{DelayNode}}.

When producing an output buffer, a <a>DelayReader</a> MUST yield exactly the
audio that was written to the corresponding <a>DelayWriter</a>
{{DelayNode|delayTime}} seconds ago.

Note: This means that channel count changes are reflected after the delay time
has passed.

<!--
████████  ██    ██ ██    ██    ███    ██     ██ ████  ██████   ██████
██     ██  ██  ██  ███   ██   ██ ██   ███   ███  ██  ██    ██ ██    ██
██     ██   ████   ████  ██  ██   ██  ████ ████  ██  ██       ██
██     ██    ██    ██ ██ ██ ██     ██ ██ ███ ██  ██  ██        ██████
██     ██    ██    ██  ████ █████████ ██     ██  ██  ██             ██
██     ██    ██    ██   ███ ██     ██ ██     ██  ██  ██    ██ ██    ██
████████     ██    ██    ██ ██     ██ ██     ██ ████  ██████   ██████
-->
<!--
 ██████   ███████  ██     ██ ████████  ████████  ████████  ██████   ██████   ███████  ████████
██    ██ ██     ██ ███   ███ ██     ██ ██     ██ ██       ██    ██ ██    ██ ██     ██ ██     ██
██       ██     ██ ████ ████ ██     ██ ██     ██ ██       ██       ██       ██     ██ ██     ██
██       ██     ██ ██ ███ ██ ████████  ████████  ██████    ██████   ██████  ██     ██ ████████
██       ██     ██ ██     ██ ██        ██   ██   ██             ██       ██ ██     ██ ██   ██
██    ██ ██     ██ ██     ██ ██        ██    ██  ██       ██    ██ ██    ██ ██     ██ ██    ██
 ██████   ███████  ██     ██ ██        ██     ██ ████████  ██████   ██████   ███████  ██     ██
-->

<h3 interface lt="DynamicsCompressorNode" id="DynamicsCompressorNode">
The {{DynamicsCompressorNode}} Interface</h3>

{{DynamicsCompressorNode}} is an
{{AudioNode}} processor implementing a dynamics
compression effect.

Dynamics compression is very commonly used in musical production and
game audio. It lowers the volume of the loudest parts of the signal
and raises the volume of the softest parts. Overall, a louder,
richer, and fuller sound can be achieved. It is especially important
in games and musical applications where large numbers of individual
sounds are played simultaneous to control the overall signal level
and help avoid clipping (distorting) the audio output to the
speakers.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-notes: Has <a>channelCount constraints</a>
    cc-mode: clamped-max
    cc-mode-notes: Has <a>channelCountMode constraints</a>
    cc-interp: speakers
    tail-time: Yes
    tail-time-notes:  This node has a <a>tail-time</a> such that this node continues to output non-silent audio with zero input due to the look-ahead delay.
</pre>

<pre class="idl">
[Exposed=Window]
interface DynamicsCompressorNode : AudioNode {
    constructor (BaseAudioContext context,
                 optional DynamicsCompressorOptions options = {});
    readonly attribute AudioParam threshold;
    readonly attribute AudioParam knee;
    readonly attribute AudioParam ratio;
    readonly attribute float reduction;
    readonly attribute AudioParam attack;
    readonly attribute AudioParam release;
};
</pre>

<h4 id="DynamicsCompressorNode-constructors">
Constructors</h4>

<dl dfn-type="constructor" dfn-for="DynamicsCompressorNode" id="dom-dynamicscompressornode-constructor-dynamicscompressornode">
    : <dfn>DynamicsCompressorNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        Let <dfn attribute for="DynamicsCompressorNode">[[internal reduction]]</dfn>
        be a private slot on <var>this</var>, that holds a floating point number, in
        decibels. Set {{[[internal reduction]]}} to 0.0.

        <pre class=argumentdef for="DynamicsCompressorNode/constructor()">
            context: The {{BaseAudioContext}} this new {{DynamicsCompressorNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{DynamicsCompressorNode}}.
        </pre>
</dl>

<h4 id="DynamicsCompressorNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="DynamicsCompressorNode">
    : <dfn>attack</dfn>
    ::
        The amount of time (in seconds) to reduce the gain by 10dB.

        <pre class=include>
        path: audioparam.include
        macros:
            default: .003
            min: 0
            max: 1
            rate: "{{AutomationRate/k-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>knee</dfn>
    ::
        A decibel value representing the range above the threshold
        where the curve smoothly transitions to the "ratio" portion.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 30
            min: 0
            max: 40
            rate: "{{AutomationRate/k-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>ratio</dfn>
    ::
        The amount of dB change in input for a 1 dB change in output.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 12
            min: 1
            max: 20
            rate: "{{AutomationRate/k-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>reduction</dfn>
    ::
        A read-only decibel value for metering purposes, representing the
        current amount of gain reduction that the compressor is applying
        to the signal. If fed no signal the value will be 0 (no gain
        reduction). When this attribute is read, return the value of the
        private slot {{[[internal reduction]]}}.

    : <dfn>release</dfn>
    ::
        The amount of time (in seconds) to increase the gain by 10dB.

        <pre class=include>
        path: audioparam.include
        macros:
            default: .25
            min: 0
            max: 1
            rate: "{{AutomationRate/k-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>threshold</dfn>
    ::
        The decibel value above which the compression will start taking effect.

        <pre class=include>
        path: audioparam.include
        macros:
            default: -24
            min: -100
            max: 0
            rate: "{{AutomationRate/k-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>
</dl>

<h4 dictionary id="DynamicsCompressorOptions">
{{DynamicsCompressorOptions}}</h4>

This specifies the options to use in constructing a
{{DynamicsCompressorNode}}. All members are
optional; if not specified the normal defaults are used in
constructing the node.

<pre class="idl">
dictionary DynamicsCompressorOptions : AudioNodeOptions {
    float attack = 0.003;
    float knee = 30;
    float ratio = 12;
    float release = 0.25;
    float threshold = -24;
};
</pre>

<h5 id="dictionary-dynamicscompressoroptions-members">
Dictionary {{DynamicsCompressorOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="DynamicsCompressorOptions">
    : <dfn>attack</dfn>
    :: The initial value for the {{DynamicsCompressorNode/attack}} AudioParam.

    : <dfn>knee</dfn>
    :: The initial value for the {{DynamicsCompressorNode/knee}} AudioParam.

    : <dfn>ratio</dfn>
    :: The initial value for the {{DynamicsCompressorNode/ratio}} AudioParam.

    : <dfn>release</dfn>
    :: The initial value for the {{DynamicsCompressorNode/release}} AudioParam.

    : <dfn>threshold</dfn>
    :: The initial value for the {{DynamicsCompressorNode/threshold}} AudioParam.
</dl>

<h4 id="DynamicsCompressorOptions-processing">
Processing</h4>

Dynamics compression can be implemented in a variety of ways. The
{{DynamicsCompressorNode}} implements a dynamics processor that
has the following characteristics:

* Fixed look-ahead (this means that an
    {{DynamicsCompressorNode}} adds a fixed latency to the signal
    chain).

* Configurable attack speed, release speed, threshold, knee
    hardness and ratio.

* Side-chaining is not supported.

* The gain reduction is reported <em>via</em> the
    <code>reduction</code> property on the
    {{DynamicsCompressorNode}}.

* The compression curve has three parts:
    * The first part is the identity: \(f(x) = x\).

    * The second part is the soft-knee portion, which MUST be a
        monotonically increasing function.

    * The third part is a linear function: \(f(x) =
        \frac{1}{ratio} \cdot x \).

    This curve MUST be continuous and piece-wise differentiable,
    and corresponds to a target output level, based on the input
    level.

Graphically, such a curve would look something like this:

<figure>
    <img alt="Graphical representation of a compression curve" src="images/compression-curve.svg" style="width: 50%">
    <figcaption>
        A typical compression curve, showing the knee portion (soft or
        hard) as well as the threshold.
    </figcaption>
</figure>

Internally, the {{DynamicsCompressorNode}} is described with a
combination of other {{AudioNode}}s, as well as a special
algorithm, to compute the gain reduction value.

The following {{AudioNode}} graph is used internally,
<code>input</code> and <code>output</code> respectively being the
input and output {{AudioNode}}, <code>context</code> the
{{BaseAudioContext}} for this {{DynamicsCompressorNode}}, and
a new class, <dfn>EnvelopeFollower</dfn>, that instantiates a
special object that behaves like an {{AudioNode}}, described
below:

<pre>
    const delay = new DelayNode(context, {delayTime: 0.006});
    const gain = new GainNode(context);
    const compression = new EnvelopeFollower();

    input.connect(delay).connect(gain).connect(output);
    input.connect(compression).connect(gain.gain);
</pre>

<figure>
    <img src="images/dynamicscompressor-internal-graph.svg" alt="Schema of
    the internal graph used by the DynamicCompressorNode">
    <figcaption>
        The graph of internal {{AudioNode}}s used as part of the
        {{DynamicsCompressorNode}} processing algorithm.
    </figcaption>
</figure>

Note: This implements the pre-delay and the application of the reduction gain.

The following algorithm describes the processing performed by an
<a>EnvelopeFollower</a> object, to be applied to the input
signal to produce the gain reduction value. An
<a>EnvelopeFollower</a> has two slots holding floating point
values. Those values persist accros invocation of this algorithm.

* Let <dfn attribute for="DynamicsCompressorNode">[[detector average]]</dfn> be a floating point
    number, initialized to 0.0.

* Let <dfn attribute for="DynamicsCompressorNode">[[compressor gain]]</dfn> be a floating point
    number, initialized to 1.0.

<div algorithm="reduction-gain">
    The following algorithm allow determining a value for
    <var>reduction gain</var>, for each sample of input, for a render
    quantum of audio.


    1. Let <var>attack</var> and <var>release</var> have the values of
        {{DynamicsCompressorNode/attack}} and {{DynamicsCompressorNode/release}}, respectively, sampled at the time of
        processing (those are <a>k-rate</a> parameters), mutiplied by the
        sample-rate of the {{BaseAudioContext}} this
        {{DynamicsCompressorNode}} is <a href="#associated">associated</a> with.

    1. Let <var>detector average</var> be the value of the slot {{[[detector average]]}}.

    1. Let <var>compressor gain</var> be the value of the slot {{[[compressor gain]]}}.

    1. For each sample <var>input</var> of the render quantum to be
        processed, execute the following steps:

        1. If the absolute value of <var>input</var> is less than
            0.0001, let <var>attenuation</var> be 1.0. Else, let
            <var>shaped input</var> be the value of applying the <a href="#compression-curve">compression curve</a> to the absolute
            value of <var>input</var>. Let <var>attenuation</var> be
            <var>shaped input</var> divided by the absolute value of <var>input</var>.

        2. Let <var>releasing</var> be `true` if
            <var>attenuation</var> is greater than <var>compressor
            gain</var>, <code>false</code> otherwise.

        3. Let <var>detector rate</var> be the result of applying the
            <a href="#detector-curve">detector curve</a> to
            <var>attenuation</var>.

        4. Subtract <var>detector average</var> from
            <var>attenuation</var>, and multiply the result by
            <var>detector rate</var>. Add this new result to <var>detector average</var>.

        5. Clamp <var>detector average</var> to a maximum of 1.0.

        6. Let <var>envelope rate</var> be the result of <a>computing the envelope rate</a> based on values of <var>attack</var> and <var>release</var>.

        7. If <var>releasing</var> is `true`, set
            <var>compressor gain</var> to be the product of
            <var>compressor gain</var> and <var>envelope rate</var>, clamped
            to a maximum of 1.0.

        8. Else, if <var>releasing</var> is <code>false</code>, let
            <var>gain increment</var> to be <var>detector average</var>
            minus <var>compressor gain</var>. Multiply <var>gain
            increment</var> by <var>envelope rate</var>, and add the result
            to <var>compressor gain</var>.

        9. Compute <var>reduction gain</var> to be <var>compressor
            gain</var> multiplied by the return value of <a>computing the
            makeup gain</a>.

        10. Compute <var>metering gain</var> to be <var>reduction gain</var>, <a href="#linear-to-decibel">converted to
            decibel</a>.

    1. Set {{[[compressor gain]]}} to <var>compressor
        gain</var>.

    1. Set {{[[detector average]]}} to <var>detector
        average</var>.

    1. <a>Atomically</a> set the internal slot {{[[internal reduction]]}}
        to the value of <var>metering gain</var>.

        Note: This step makes the metering gain update once per block, at the
        end of the block processing.
</div>

The makeup gain is a fixed gain stage that only depends on ratio,
knee and threshold parameter of the compressor, and not on the
input signal. The intent here is to increase the output level of
the compressor so it is comparable to the input level.

<div algorithm="computing makeup gain">
    <dfn>Computing the makeup gain</dfn> means executing the following steps:

    1. Let <var>full range gain</var> be the value returned by
        applying the <a>compression curve</a> to the value 1.0.

    2. Let <var>full range makeup gain</var> be the inverse of <var>full
        range gain</var>.

    3. Return the result of taking the 0.6 power of <var>full range makeup
        gain</var>.
</div>

<div algorithm="computing envelope rate">
    <dfn>Computing the envelope rate</dfn> is done
    by applying a function to the ratio of the <var>compressor
    gain</var> and the <var>detector average</var>. User-agents are
    allowed to choose the shape of the envelope function. However, this
    function MUST respect the following constraints:

    * The envelope rate MUST be the calculated from the ratio of the
        <var>compressor gain</var> and the <var>detector average</var>.

        Note: When attacking, this number less than or equal to 1, when
        releasing, this number is strictly greater than 1.

    * The attack curve MUST be a continuous, monotonically increasing
        function in the range \([0, 1]\).  The shape of this curve MAY be controlled by {{DynamicsCompressorNode/attack}}.

    * The release curve MUST be a continuous, monotonically
        decreasing function that is always greater than 1.  The shape of this curve MAY be controlled by {{DynamicsCompressorNode/release}}.

    This operation returns the value computed by applying this function
    to the ratio of <var>compressor gain</var> and <var>detector
    average</var>.
</div>

Applying the <dfn id="detector-curve">detector curve</dfn> to the
change rate when attacking or releasing allow implementing
<em>adaptive release</em>. It is a function that MUST respect the
following constraints:

* The output of the function MUST be in \([0,1]\).

* The function MUST be monotonically increasing, continuous.

Note: It is allowed, for example, to have a compressor that performs an
<em>adaptive release</em>, that is, releasing faster the harder the
compression, or to have curves for attack and release that are not
of the same shape.

<div algorithm="apply decompression">
    Applying a <dfn>compression curve</dfn> to a value means computing
    the value of this sample when passed to a function, and returning
    the computed value. This function MUST respect the following
    characteristics:

    1. Let <var>threshold</var> and <var>knee</var> have the
        values of {{DynamicsCompressorNode/threshold}} and
        {{DynamicsCompressorNode/knee}}, respectively,
        [=decibels to linear gain unit|converted to linear
        units=] and sampled at the time of processing of this
        block (as [=k-rate=] parameters).
    
    1. Calculate the sum of {{DynamicsCompressorNode/threshold}} plus
        {{DynamicsCompressorNode/knee}} also sampled at the time
        of processing of this block (as [=k-rate=] parameters).
        
    1. Let <var>knee end threshold</var> have the value of this
        sum [=decibels to linear gain unit|converted to linear
        units=].

    1. Let <var>ratio</var> have the value of the
        {{DynamicsCompressorNode/ratio}}, sampled at the time
        of processing of this block (as a [=k-rate=]
        parameter).

    1. This function is the identity up to the value of the linear
        <var>threshold</var> (i.e., \(f(x) = x\)).

    1. From the <var>threshold</var> up to the
        <var>knee end threshold</var>, User-Agents can choose the
        curve shape. The whole function MUST be monotonically
        increasing and continuous.

        Note: If the <var>knee</var> is 0, the
        {{DynamicsCompressorNode}} is called a hard-knee compressor.

    1. This function is linear, based on the <var>ratio</var>, after the
        <var>threshold</var> and the soft knee (i.e., \(f(x) =
        \frac{1}{ratio} \cdot x \)).
</div>

<div algorithm="convert linear to db">
    Converting a value \(v\) in <dfn id="linear-to-decibel">linear gain
    unit to decibel</dfn> means executing the following steps:

    1. If \(v\) is equal to zero, return -1000.

    2. Else, return \( 20 \, \log_{10}{v} \).
</div>

<div algorithm="convert db to linear">
    Converting a value \(v\) in <dfn>decibels to
    linear gain unit</dfn> means returning \(10^{v/20}\).
</div>


<!--
 ██████      ███    ████ ██    ██ ██    ██  ███████  ████████  ████████
██    ██    ██ ██    ██  ███   ██ ███   ██ ██     ██ ██     ██ ██
██         ██   ██   ██  ████  ██ ████  ██ ██     ██ ██     ██ ██
██   ████ ██     ██  ██  ██ ██ ██ ██ ██ ██ ██     ██ ██     ██ ██████
██    ██  █████████  ██  ██  ████ ██  ████ ██     ██ ██     ██ ██
██    ██  ██     ██  ██  ██   ███ ██   ███ ██     ██ ██     ██ ██
 ██████   ██     ██ ████ ██    ██ ██    ██  ███████  ████████  ████████
-->

<h3 interface lt="GainNode" id="GainNode">
The {{GainNode}} Interface</h3>

Changing the gain of an audio signal is a fundamental operation in
audio applications. This
interface is an {{AudioNode}} with a single input and
single output:

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: No
</pre>

Each sample of each channel of the input data of the
{{GainNode}} MUST be multiplied by the
<a>computedValue</a> of the {{GainNode/gain}} {{AudioParam}}.

<pre class="idl">
[Exposed=Window]
interface GainNode : AudioNode {
    constructor (BaseAudioContext context, optional GainOptions options = {});
    readonly attribute AudioParam gain;
};
</pre>

<h4 id="GainNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="GainNode" id="dom-gainnode-constructor-gainnode">
    : <dfn>GainNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="GainNode/constructor()">
            context: The {{BaseAudioContext}} this new {{GainNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter values for this {{GainNode}}.
        </pre>
</dl>

<h4 id="GainNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="GainNode">
    : <dfn>gain</dfn>
    ::
        Represents the amount of gain to apply.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 1
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
        </pre>
</dl>

<h4 dictionary id="GainOptions">
{{GainOptions}}</h4>

This specifies options to use in constructing a
{{GainNode}}. All members are optional; if not
specified, the normal defaults are used in constructing the node.

<pre class="idl">
dictionary GainOptions : AudioNodeOptions {
    float gain = 1.0;
};
</pre>

<h5 id="dictionary-gainoptions-members">
Dictionary {{GainOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="GainOptions">
    : <dfn>gain</dfn>
    :: The initial gain value for the {{GainNode/gain}} AudioParam.
</dl>


<!--
████ ████ ████████  ████████ ████ ██       ████████ ████████ ████████
 ██   ██  ██     ██ ██        ██  ██          ██    ██       ██     ██
 ██   ██  ██     ██ ██        ██  ██          ██    ██       ██     ██
 ██   ██  ████████  ██████    ██  ██          ██    ██████   ████████
 ██   ██  ██   ██   ██        ██  ██          ██    ██       ██   ██
 ██   ██  ██    ██  ██        ██  ██          ██    ██       ██    ██
████ ████ ██     ██ ██       ████ ████████    ██    ████████ ██     ██
-->

<h3 interface lt="IIRFilterNode" id="IIRFilterNode">
The {{IIRFilterNode}} Interface</h3>

{{IIRFilterNode}} is an {{AudioNode}}
processor implementing a general <a href="https://en.wikipedia.org/wiki/Infinite_impulse_response">IIR Filter</a>. In general, it is best
to use {{BiquadFilterNode}}'s to implement
higher-order filters for the following reasons:

* Generally less sensitive to numeric issues

* Filter parameters can be automated

* Can be used to create all even-ordered IIR filters

However, odd-ordered filters cannot be created, so if such filters
are needed or automation is not needed, then IIR filters may be
appropriate.

Once created, the coefficients of the IIR filter cannot be changed.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: Yes
    tail-time-notes: Continues to output non-silent audio with zero input. Since this is an IIR filter, the filter produces non-zero input forever, but in practice, this can be limited after some finite time where the output is sufficiently close to zero. The actual time depends on the filter coefficients.
</pre>

The number of channels of the output always equals the number of
channels of the input.

<pre class="idl">
[Exposed=Window]
interface IIRFilterNode : AudioNode {
    constructor (BaseAudioContext context, IIRFilterOptions options);
    undefined getFrequencyResponse (Float32Array frequencyHz,
                                    Float32Array magResponse,
                                    Float32Array phaseResponse);
};
</pre>

<h4 id="IIRFilterNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="IIRFilterNode" id="dom-iirfilternode-constructor-iirfilternode">
    : <dfn>IIRFilterNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="IIRFilterNode/constructor()">
            context: The {{BaseAudioContext}} this new {{IIRFilterNode}} will be <a href="#associated">associated</a> with.
            options: Initial parameter value for this {{IIRFilterNode}}.
        </pre>
</dl>

<h4 id="IIRFilterNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="IIRFilterNode">
    : <dfn>getFrequencyResponse(frequencyHz, magResponse, phaseResponse)</dfn>
    ::
        <span class="synchronous">Given the current filter parameter
        settings, synchronously calculates the frequency response for the
        specified frequencies. The three parameters MUST be
        {{Float32Array}}s of the same length, or an
        {{InvalidAccessError}} MUST be thrown.</span>

        <pre class=argumentdef for="IIRFilterNode/getFrequencyResponse()">
            frequencyHz: This parameter specifies an array of frequencies, in Hz, at which the response values will be calculated.
            magResponse: This parameter specifies an output array receiving the linear magnitude response values. If a value in the <code>frequencyHz</code> parameter is not within [0, sampleRate/2], where <code>sampleRate</code> is the value of the {{BaseAudioContext/sampleRate}} property of the {{AudioContext}}, the corresponding value at the same index of the <code>magResponse</code> array MUST be <code>NaN</code>.
            phaseResponse: This parameter specifies an output array receiving the phase response values in radians. If a value in the <code>frequencyHz</code> parameter is not within [0; sampleRate/2], where <code>sampleRate</code> is the value of the {{BaseAudioContext/sampleRate}} property of the {{AudioContext}}, the corresponding value at the same index of the <code>phaseResponse</code> array MUST be <code>NaN</code>.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>

<h4 dictionary id="IIRFilterOptions">
{{IIRFilterOptions}}</h4>

The <code>IIRFilterOptions</code> dictionary is used to specify the
filter coefficients of the {{IIRFilterNode}}.

<xmp class="idl">
dictionary IIRFilterOptions : AudioNodeOptions {
    required sequence<double> feedforward;
    required sequence<double> feedback;
};
</xmp>

<h5 id="dictionary-iirfilteroptions-members">
Dictionary {{IIRFilterOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="IIRFilterOptions">
    : <dfn>feedforward</dfn>
    ::
        The feedforward coefficients for the
        {{IIRFilterNode}}. This member is required.  See {{BaseAudioContext/createIIRFilter()/feedforward}} argument of {{BaseAudioContext/createIIRFilter()}} for other constraints.

    : <dfn>feedback</dfn>
    ::
        The feedback coefficients for the
        {{IIRFilterNode}}. This member is required.  See {{BaseAudioContext/createIIRFilter()/feedback}} argument of {{BaseAudioContext/createIIRFilter()}} for other constraints.
</dl>

<h4 id="IIRFilterNode-filter-definition">
Filter Definition</h4>

Let \(b_m\) be the <code>feedforward</code> coefficients and
\(a_n\) be the <code>feedback</code> coefficients specified by
{{BaseAudioContext/createIIRFilter()}} or the {{IIRFilterOptions}} dictionary for the {{IIRFilterNode/IIRFilterNode()|constructor}}. Then the
transfer function of the general IIR filter is given by

<pre nohighlight>
$$
    H(z) = \frac{\sum_{m=0}^{M} b_m z^{-m}}{\sum_{n=0}^{N} a_n z^{-n}}
$$
</pre>

where \(M + 1\) is the length of the \(b\) array and \(N + 1\) is
the length of the \(a\) array. The coefficient \(a_0\) MUST not be 0 (see {{BaseAudioContext/createIIRFilter()/feedback|feedback parameter}} for {{BaseAudioContext/createIIRFilter()}}).
At least one of \(b_m\) MUST be non-zero (see {{BaseAudioContext/createIIRFilter()/feedforward|feedforward parameter}} for {{BaseAudioContext/createIIRFilter()}}).

Equivalently, the time-domain equation is:

<pre nohighlight>
$$
    \sum_{k=0}^{N} a_k y(n-k) = \sum_{k=0}^{M} b_k x(n-k)
$$
</pre>

The initial filter state is the all-zeroes state.

Note: The UA may produce a warning to notify the user that NaN values have occurred in the filter state.  This is usually indicative of an unstable filter.


<!--
██     ██ ████████ ████████  ████    ███    ████████ ██       ████████ ██     ██ ████████ ██    ██ ████████
███   ███ ██       ██     ██  ██    ██ ██   ██       ██       ██       ███   ███ ██       ███   ██    ██
████ ████ ██       ██     ██  ██   ██   ██  ██       ██       ██       ████ ████ ██       ████  ██    ██
██ ███ ██ ██████   ██     ██  ██  ██     ██ ██████   ██       ██████   ██ ███ ██ ██████   ██ ██ ██    ██
██     ██ ██       ██     ██  ██  █████████ ██       ██       ██       ██     ██ ██       ██  ████    ██
██     ██ ██       ██     ██  ██  ██     ██ ██       ██       ██       ██     ██ ██       ██   ███    ██
██     ██ ████████ ████████  ████ ██     ██ ████████ ████████ ████████ ██     ██ ████████ ██    ██    ██
-->
<!--
   ███    ██     ██ ████████  ████  ███████   ██████   ███████  ██     ██ ████████   ██████  ████████
  ██ ██   ██     ██ ██     ██  ██  ██     ██ ██    ██ ██     ██ ██     ██ ██     ██ ██    ██ ██
 ██   ██  ██     ██ ██     ██  ██  ██     ██ ██       ██     ██ ██     ██ ██     ██ ██       ██
██     ██ ██     ██ ██     ██  ██  ██     ██  ██████  ██     ██ ██     ██ ████████  ██       ██████
█████████ ██     ██ ██     ██  ██  ██     ██       ██ ██     ██ ██     ██ ██   ██   ██       ██
██     ██ ██     ██ ██     ██  ██  ██     ██ ██    ██ ██     ██ ██     ██ ██    ██  ██    ██ ██
██     ██  ███████  ████████  ████  ███████   ██████   ███████   ███████  ██     ██  ██████  ████████
-->

<h3 interface lt="MediaElementAudioSourceNode" id="MediaElementAudioSourceNode">
The {{MediaElementAudioSourceNode}} Interface</h3>

This interface represents an audio source from an <{audio}>
or <{video}> element.

<pre class=include>
path: audionode-noinput.include
macros:
    noo: 1
    tail-time: No
</pre>

The number of channels of the output corresponds to the number of
channels of the media referenced by the
{{HTMLMediaElement}}. Thus, changes to the media element's
<code>src</code> attribute can change the number of channels output
by this node.

If the sample rate of the {{HTMLMediaElement}} differs from the sample
rate of the associated {{AudioContext}}, then the output from the
{{HTMLMediaElement}} must be resampled to match the context's
{{BaseAudioContext/sampleRate|sample rate}}.

A {{MediaElementAudioSourceNode}} is created given an
{{HTMLMediaElement}} using the {{AudioContext}}
{{createMediaElementSource()}} method or the {{MediaElementAudioSourceOptions/mediaElement}} member of the {{MediaElementAudioSourceOptions}} dictionary for the {{MediaElementAudioSourceNode/MediaElementAudioSourceNode()|constructor}}.

The number of channels of the single output equals the number of
channels of the audio referenced by the {{HTMLMediaElement}}
passed in as the argument to {{createMediaElementSource()}},
or is 1 if the {{HTMLMediaElement}} has no audio.

The {{HTMLMediaElement}} MUST behave in an identical fashion
after the {{MediaElementAudioSourceNode}} has been created,
<em>except</em> that the rendered audio will no longer be heard
directly, but instead will be heard as a consequence of the
{{MediaElementAudioSourceNode}} being connected through the
routing graph. Thus pausing, seeking, volume, <code>src</code>
attribute changes, and other aspects of the
{{HTMLMediaElement}} MUST behave as they normally would if
<em>not</em> used with a {{MediaElementAudioSourceNode}}.

<pre class="example" highlight="js">
    const mediaElement = document.getElementById('mediaElementID');
    const sourceNode = context.createMediaElementSource(mediaElement);
    sourceNode.connect(filterNode);
</pre>

<pre class="idl">
[Exposed=Window]
interface MediaElementAudioSourceNode : AudioNode {
    constructor (AudioContext context, MediaElementAudioSourceOptions options);
    [SameObject] readonly attribute HTMLMediaElement mediaElement;
};
</pre>

<h4 id="MediaElementAudioSourceNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="MediaElementAudioSourceNode">
    : <dfn>MediaElementAudioSourceNode(context, options)</dfn>
    ::
        1. <a href="#audionode-constructor-init">initialize the AudioNode</a>
            <var>this</var>, with <var>context</var> and <var>options</var> as arguments.

        <pre class=argumentdef for="MediaElementAudioSourceNode/constructor()">
            context: The {{AudioContext}} this new {{MediaElementAudioSourceNode}} will be <a href="#associated">associated</a> with.
            options: Initial parameter value for this {{MediaElementAudioSourceNode}}.
        </pre>
</dl>

<h4 id="MediaElementAudioSourceNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="MediaElementAudioSourceNode">
    : <dfn>mediaElement</dfn>
    ::
        The {{HTMLMediaElement}} used when constructing this
        {{MediaElementAudioSourceNode}}.
</dl>

<h4 dictionary id="MediaElementAudioSourceOptions">
{{MediaElementAudioSourceOptions}}</h4>

This specifies the options to use in constructing a
{{MediaElementAudioSourceNode}}.

<pre class="idl">
dictionary MediaElementAudioSourceOptions {
    required HTMLMediaElement mediaElement;
};
</pre>

<h5 id="dictionary-mediaelementaudiosourceoptions-members">
Dictionary {{MediaElementAudioSourceOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="MediaElementAudioSourceOptions">
    : <dfn>mediaElement</dfn>
    :: The media element that will be re-routed. This MUST be specified.
</dl>

<h4 id="MediaElementAudioSourceOptions-security">
Security with MediaElementAudioSourceNode and Cross-Origin Resources</h4>

{{HTMLMediaElement}} allows the playback of cross-origin
resources. Because Web Audio allows inspection of the content of
the resource (e.g. using a {{MediaElementAudioSourceNode}}, and
an {{AudioWorkletNode}} or {{ScriptProcessorNode}} to read the samples), information
leakage can occur if scripts from one [[html#origin|origin]]
inspect the content of a resource from another
[[html#origin|origin]].

To prevent this, a {{MediaElementAudioSourceNode}} MUST output
<em>silence</em> instead of the normal output of the
{{HTMLMediaElement}} if it has been created using an
{{HTMLMediaElement}} for which the execution of the
<a href="https://fetch.spec.whatwg.org/#fetching">fetch
algorithm</a> [[!FETCH]] labeled the resource as
<a href="https://html.spec.whatwg.org/#cors-cross-origin">CORS-cross-origin</a>.


<!-- Big Text: MediaStream -->
<!-- Big Text: Audio -->
<!-- Big Text: Destination -->

<h3 interface lt="MediaStreamAudioDestinationNode" id="MediaStreamAudioDestinationNode">
The {{MediaStreamAudioDestinationNode}} Interface</h3>

This interface is an audio destination representing a
{{MediaStream}} with a single {{MediaStreamTrack}}
whose <code>kind</code> is <code>"audio"</code>. This {{MediaStream}} is
created when the node is created and is accessible via the
{{MediaStreamAudioDestinationNode/stream}} attribute. This stream can be used in a similar way
as a {{MediaStream}} obtained via
{{getUserMedia()}}, and can, for example, be sent to a
remote peer using the <code>RTCPeerConnection</code> (described in
[[!webrtc]]) <code>addStream()</code> method.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 0
    cc: 2
    cc-mode: explicit
    cc-interp: speakers
    tail-time: No
</pre>

The number of channels of the input is by default 2 (stereo).

<pre class="idl">
[Exposed=Window]
interface MediaStreamAudioDestinationNode : AudioNode {
    constructor (AudioContext context, optional AudioNodeOptions options = {});
    readonly attribute MediaStream stream;
};
</pre>

<h4 id="MediaStreamAudioDestinationNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="MediaStreamAudioDestinationNode">
    : <dfn>MediaStreamAudioDestinationNode(context, options)</dfn>
    ::
        1. <a href="#audionode-constructor-init">Initialize the AudioNode</a>
            <var>this</var>, with <var>context</var> and <var>options</var> as arguments.

        <pre class=argumentdef for="MediaStreamAudioDestinationNode/constructor()">
            context: The {{BaseAudioContext}} this new {{MediaStreamAudioDestinationNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{MediaStreamAudioDestinationNode}}.
        </pre>
</dl>

<h4 id="MediaStreamAudioDestinationNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="MediaStreamAudioDestinationNode">
    : <dfn>stream</dfn>
    ::
        A {{MediaStream}} containing a single {{MediaStreamTrack}} with the same
        number of channels as the node itself, and whose
        <code>kind</code> attribute has the value <code>"audio"</code>.
</dl>


<!-- Big Text: MediaStream -->
<!-- Big Text: AudioSource -->

<h3 interface lt="MediaStreamAudioSourceNode" id="MediaStreamAudioSourceNode">
The {{MediaStreamAudioSourceNode}} Interface</h3>

This interface represents an audio source from a
{{MediaStream}}.

<pre class=include>
path: audionode-noinput.include
macros:
    noo: 1
    tail-time: No
</pre>

The number of channels of the output corresponds to the number of channels of
the {{MediaStreamTrack}}. When the
{{MediaStreamTrack}} ends, this
{{AudioNode}} outputs one channel of silence.

If the sample rate of the {{MediaStreamTrack}} differs from the sample
rate of the associated {{AudioContext}}, then the output of the
{{MediaStreamTrack}} is resampled to match the context's
{{BaseAudioContext/sampleRate|sample rate}}.

<pre class="idl">
[Exposed=Window]
interface MediaStreamAudioSourceNode : AudioNode {
    constructor (AudioContext context, MediaStreamAudioSourceOptions options);
    [SameObject] readonly attribute MediaStream mediaStream;
};
</pre>

<h4 id="MediaStreamAudioSourceNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="MediaStreamAudioSourceNode">
    : <dfn>MediaStreamAudioSourceNode(context, options)</dfn>
    ::
            1. If the {{MediaStreamAudioSourceOptions/mediaStream}} member of
                {{MediaStreamAudioSourceNode/constructor(context, options)/options!!argument}} does not reference a
                {{MediaStream}} that has at least one
                {{MediaStreamTrack}} whose
                <code>kind</code> attribute has the value <code>"audio"</code>,
                throw an {{InvalidStateError}} and abort these steps. Else, let
                this stream be <var>inputStream</var>.
            1. Let <var>tracks</var> be the list of all
                {{MediaStreamTrack}}s of
                <var>inputStream</var> that have a <code>kind</code> of
                <code>"audio"</code>.
            1. Sort the elements in <var>tracks</var> based on their <code>id</code>
                attribute using an ordering on sequences of [=code unit=]
                values.
            1. <a href="#audionode-constructor-init">Initialize the AudioNode</a>
                <var>this</var>, with <var>context</var> and <var>options</var> as arguments.
            1. Set an internal slot <dfn attribute
                for="MediaStreamAudioSourceNode">[[input track]]</dfn> on this
                {{MediaStreamAudioSourceNode}} to be the first element of
                <var>tracks</var>.  This is the track used as the input audio for this
                {{MediaStreamAudioSourceNode}}.

            After construction, any change to the
            {{MediaStream}} that was passed to
            the constructor do not affect the underlying output of this {{AudioNode}}.

            The slot {{[[input track]]}} is only used to keep a reference to the
            {{MediaStreamTrack}}.

            Note: This means that when removing the track chosen by the constructor
            of the {{MediaStreamAudioSourceNode}} from the
            {{MediaStream}} passed into this
            constructor, the {{MediaStreamAudioSourceNode}} will still take its input
            from the same track.

            Note: The behaviour for picking the track to output is arbitrary for
            legacy reasons. {{MediaStreamTrackAudioSourceNode}} can be used
            instead to be explicit about which track to use as input.

        <pre class=argumentdef for="MediaStreamAudioSourceNode/constructor()">
            context: The {{AudioContext}} this new {{MediaStreamAudioSourceNode}} will be <a href="#associated">associated</a> with.
            options: Initial parameter value for this {{MediaStreamAudioSourceNode}}.
        </pre>
</dl>

<h4 id="MediaStreamAudioSourceNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="MediaStreamAudioSourceNode">
    : <dfn>mediaStream</dfn>
    :: The {{MediaStream}} used when constructing this {{MediaStreamAudioSourceNode}}.
</dl>

<h4 dictionary lt="MediaStreamAudioSourceOptions" id="MediaStreamAudioSourceOptions">
{{MediaStreamAudioSourceOptions}}</h4>

This specifies the options for constructing a {{MediaStreamAudioSourceNode}}.

<pre class="idl">
dictionary MediaStreamAudioSourceOptions {
    required MediaStream mediaStream;
};
</pre>

<h5 id="dictionary-mediastreamaudiosourceoptions-members">
Dictionary {{MediaStreamAudioSourceOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="MediaStreamAudioSourceOptions">
    : <dfn>mediaStream</dfn>
    :: The media stream that will act as a source. This MUST be specified.
</dl>


<!-- Big Text: MediaStream -->
<!-- Big Text: TrackAudio -->
<!-- Big Text: Source -->

<h3 interface lt="MediaStreamTrackAudioSourceNode" id="MediaStreamTrackAudioSourceNode">
The {{MediaStreamTrackAudioSourceNode}} Interface</h3>

This interface represents an audio source from a {{MediaStreamTrack}}.

<pre class=include>
path: audionode-noinput.include
macros:
    noo: 1
    tail-time: No
</pre>

The number of channels of the output corresponds to the number of
channels of the {{MediaStreamTrackAudioSourceOptions/mediaStreamTrack}}.

If the sample rate of the {{MediaStreamTrack}} differs from the sample
rate of the associated {{AudioContext}}, then the output of the
{{MediaStreamTrackAudioSourceOptions/mediaStreamTrack}} is resampled
to match the context's {{BaseAudioContext/sampleRate|sample rate}}.

<pre class="idl">
[Exposed=Window]
interface MediaStreamTrackAudioSourceNode : AudioNode {
    constructor (AudioContext context, MediaStreamTrackAudioSourceOptions options);
};
</pre>

<h4 id="MediaStreamTrackAudioSourceNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="MediaStreamTrackAudioSourceNode">
    : <dfn>MediaStreamTrackAudioSourceNode(context, options)</dfn>
    ::
        1. If the {{MediaStreamTrackAudioSourceOptions/mediaStreamTrack}}'s
            <code>kind</code> attribute is not <code>"audio"</code>, throw an
            {{InvalidStateError}} and abort these steps.
        1. <a href="#audionode-constructor-init">Initialize the AudioNode</a>
            <var>this</var>, with <var>context</var> and <var>options</var> as arguments.

        <pre class=argumentdef for="MediaStreamTrackAudioSourceNode/constructor()">
            context: The {{AudioContext}} this new {{MediaStreamTrackAudioSourceNode}} will be <a href="#associated">associated</a> with.
            options: Initial parameter value for this {{MediaStreamTrackAudioSourceNode}}.
        </pre>
</dl>

<h4 dictionary id="MediaStreamTrackAudioSourceOptions">
{{MediaStreamTrackAudioSourceOptions}}</h4>

This specifies the options for constructing a
{{MediaStreamTrackAudioSourceNode}}. This is
required.

<pre class="idl">
dictionary MediaStreamTrackAudioSourceOptions {
    required MediaStreamTrack mediaStreamTrack;
};
</pre>

<h5 id="dictionary-mediastreamtrackaudiosourceoptions-members">
Dictionary {{MediaStreamTrackAudioSourceOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="MediaStreamTrackAudioSourceOptions">
    : <dfn>mediaStreamTrack</dfn>
    ::
        The media stream track that will act as a source. <span class="synchronous">If this
        {{MediaStreamTrack}} <code>kind</code> attribute is
        not <code>"audio"</code>, an {{InvalidStateError}}
        MUST be thrown.</span>
</dl>


<!-- Big Text: Oscillator -->

<h3 interface lt="OscillatorNode" id="OscillatorNode">
The {{OscillatorNode}} Interface</h3>

{{OscillatorNode}} represents an audio source
generating a periodic waveform. It can be set to a few commonly used
waveforms. Additionally, it can be set to an arbitrary periodic
waveform through the use of a {{PeriodicWave}}
object.

Oscillators are common foundational building blocks in audio
synthesis. An OscillatorNode will start emitting sound at the time
specified by the {{AudioScheduledSourceNode/start()}} method.

Mathematically speaking, a <em>continuous-time</em> periodic waveform
can have very high (or infinitely high) frequency information when
considered in the frequency domain. When this waveform is sampled as
a discrete-time digital audio signal at a particular sample-rate,
then care MUST be taken to discard (filter out) the high-frequency
information higher than the <a>Nyquist frequency</a> before
converting the waveform to a digital form. If this is not done, then
<a href="https://en.wikipedia.org/wiki/Aliasing"><em>aliasing</em></a> of higher frequencies (than the <a>Nyquist
frequency</a>) will fold back as mirror images into frequencies lower
than the <a>Nyquist frequency</a>. In many cases this will cause
audibly objectionable artifacts. This is a basic and well-understood
principle of audio DSP.

There are several practical approaches that an implementation may
take to avoid this aliasing. Regardless of approach, the
<em>idealized</em> discrete-time digital audio signal is well defined
mathematically. The trade-off for the implementation is a matter of
implementation cost (in terms of CPU usage) versus fidelity to
achieving this ideal.

It is expected that an implementation will take some care in
achieving this ideal, but it is reasonable to consider lower-quality,
less-costly approaches on lower-end hardware.

Both {{OscillatorNode/frequency}} and {{OscillatorNode/detune}} are <a>a-rate</a>
parameters, and form a <a>compound parameter</a>. They are used
together to determine a <dfn>computedOscFrequency</dfn> value:

<pre>
    computedOscFrequency(t) = frequency(t) * pow(2, detune(t) / 1200)
</pre>

The OscillatorNode's instantaneous phase at each time is the definite
time integral of <a>computedOscFrequency</a>, assuming a phase angle
of zero at the node's exact start time. Its <a>nominal range</a> is
[-<a>Nyquist frequency</a>, <a>Nyquist frequency</a>].

The single output of this node consists of one channel (mono).

<pre class=include>
path: audionode.include
macros:
    noi: 0
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: No
</pre>

<pre class="idl">
enum OscillatorType {
    "sine",
    "square",
    "sawtooth",
    "triangle",
    "custom"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="OscillatorType">
    <caption>{{OscillatorType}} enumeration description</caption>
    <thead>
        <th>Enum value</th><th>Description</th>
    <tbody>
        <tr><td>"<dfn>sine</dfn>" <td>A sine wave
        <tr><td>"<dfn>square</dfn>" <td>A square wave of duty period 0.5
        <tr><td>"<dfn>sawtooth</dfn>" <td>A sawtooth wave
        <tr><td>"<dfn>triangle</dfn>" <td>A triangle wave
        <tr><td>"<dfn>custom</dfn>" <td>A custom periodic wave
</table>
</div>

<pre class="idl">
[Exposed=Window]
interface OscillatorNode : AudioScheduledSourceNode {
    constructor (BaseAudioContext context, optional OscillatorOptions options = {});
    attribute OscillatorType type;
    readonly attribute AudioParam frequency;
    readonly attribute AudioParam detune;
    undefined setPeriodicWave (PeriodicWave periodicWave);
};
</pre>

<h4 id="OscillatorNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="OscillatorNode">
    : <dfn>OscillatorNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="OscillatorNode/constructor()">
            context: The {{BaseAudioContext}} this new {{OscillatorNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{OscillatorNode}}.
        </pre>
</dl>

<h4 id="OscillatorNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="OscillatorNode">
    : <dfn>detune</dfn>
    ::
        A detuning value (in <a href="https://en.wikipedia.org/wiki/Cent_(music)">cents</a>) which will offset the
        {{OscillatorNode/frequency}} by the given amount. Its default
        <code>value</code> is 0. This parameter is <a>a-rate</a>. It
        forms a <a>compound parameter</a> with {{OscillatorNode/frequency}}
        to form the <a>computedOscFrequency</a>.  The nominal
        range listed below allows this parameter to detune the
        {{OscillatorNode/frequency}} over the entire possible
        range of frequencies.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: \(\approx -153600\)
            min-notes:
            max: \(\approx 153600\)
            max-notes: This value is approximately \(1200\ \log_2 \mathrm{FLT\_MAX}\) where FLT_MAX is the largest {{float}} value.
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>frequency</dfn>
    ::
        The frequency (in Hertz) of the periodic waveform. Its default
        <code>value</code> is 440. This parameter is <a>a-rate</a>. It
        forms a <a>compound parameter</a> with {{OscillatorNode/detune}} to
        form the <a>computedOscFrequency</a>. Its <a>nominal range</a>
        is [-<a>Nyquist frequency</a>, <a>Nyquist frequency</a>].

        <pre class=include>
        path: audioparam.include
        macros:
            default: 440
            min: -<a>Nyquist frequency</a>
            max: <a>Nyquist frequency</a>
            rate: "{{AutomationRate/a-rate}}"
        </pre>

    : <dfn>type</dfn>
    ::  The shape of the periodic waveform. It may directly be set to any
        of the type constant values except for "{{OscillatorType/custom}}". <span class="synchronous">Doing so MUST throw an
        {{InvalidStateError}} exception.</span> The
        {{OscillatorNode/setPeriodicWave()}} method can be
        used to set a custom waveform, which results in this attribute
        being set to "{{OscillatorType/custom}}". The default value is "{{OscillatorType/sine}}". When this
        attribute is set, the phase of the oscillator MUST be conserved.
</dl>

<h4 id="OscillatorNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="OscillatorNode">
    : <dfn>setPeriodicWave(periodicWave)</dfn>
    ::
        Sets an arbitrary custom periodic waveform given a {{PeriodicWave}}.

        <pre class=argumentdef for="OscillatorNode/setPeriodicWave()">
            periodicWave: custom waveform to be used by the oscillator
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>

<h4 dictionary id="OscillatorOptions">
{{OscillatorOptions}}</h4>

This specifies the options to be used when constructing an
{{OscillatorNode}}. All of the members are
optional; if not specified, the normal default values are used for
constructing the oscillator.

<pre class="idl">
dictionary OscillatorOptions : AudioNodeOptions {
    OscillatorType type = "sine";
    float frequency = 440;
    float detune = 0;
    PeriodicWave periodicWave;
};
</pre>

<h5 id="dictionary-oscillatoroptions-members">
Dictionary {{OscillatorOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="OscillatorOptions">
    : <dfn>detune</dfn>
    :: The initial detune value for the {{OscillatorNode}}.

    : <dfn>frequency</dfn>
    :: The initial frequency for the {{OscillatorNode}}.

    : <dfn>periodicWave</dfn>
    ::
        The {{PeriodicWave}} for the
        {{OscillatorNode}}. If this is specified, then
        any valid value for {{OscillatorOptions/type}} is ignored; it is
        treated as if "{{OscillatorType/custom}}" were specified.

    : <dfn>type</dfn>
    ::
        The type of oscillator to be constructed. If this is set to
        "custom" without also specifying a {{OscillatorOptions/periodicWave}}, then an
        <span class="synchronous">{{InvalidStateError}}
        exception MUST be thrown</span>. If {{OscillatorOptions/periodicWave}} is specified,
        then any valid value for {{OscillatorOptions/type}} is ignored; it is
        treated as if it were set to "custom".
</dl>

<h4 id="basic-waveform-phase">
Basic Waveform Phase</h4>

The idealized mathematical waveforms for the various oscillator
types are defined below. In summary, all waveforms are defined
mathematically to be an odd function with a positive slope at time 0.
The actual waveforms produced by the oscillator may differ to
prevent aliasing affects.

The oscillator MUST produce the same result as if a {{PeriodicWave}},
with the appropriate <a href="#oscillator-coefficients">Fourier
series</a> and with {{PeriodicWaveConstraints/disableNormalization}} set to false, were used to create these
basic waveforms.

: "{{OscillatorType/sine}}"
::
    The waveform for sine oscillator is:

    <pre nohighlight>
    $$
        x(t) = \sin t
    $$
    </pre>

: "{{OscillatorType/square}}"
::
    The waveform for the square wave oscillator is:

    <pre nohighlight>
    $$
        x(t) = \begin{cases}
                     1 & \mbox{for } 0≤ t &lt; \pi \\
                     -1 & \mbox{for } -\pi &lt; t &lt; 0.
                     \end{cases}
    $$
    </pre>

    This is extended to all \(t\) by using the fact that the
    waveform is an odd function with period \(2\pi\).

: "{{OscillatorType/sawtooth}}"
::
    The waveform for the sawtooth oscillator is the ramp:

    <pre nohighlight>
    $$
        x(t) = \frac{t}{\pi} \mbox{ for } -\pi &lt; t ≤ \pi;
    $$
    </pre>

    This is extended to all \(t\) by using the fact that the
    waveform is an odd function with period \(2\pi\).

: "{{OscillatorType/triangle}}"
::
    The waveform for the triangle oscillator is:

    <pre nohighlight>
    $$
        x(t) = \begin{cases}
                         \frac{2}{\pi} t & \mbox{for } 0 ≤ t ≤ \frac{\pi}{2} \\
                         1-\frac{2}{\pi} \left(t-\frac{\pi}{2}\right) & \mbox{for }
                         \frac{\pi}{2} &lt; t ≤ \pi.
                     \end{cases}
    $$
    </pre>

    This is extended to all \(t\) by using the fact that the
    waveform is an odd function with period \(2\pi\).


<!-- Big Text: Panner -->

<h3 interface lt="PannerNode" id="PannerNode">
The {{PannerNode}} Interface</h3>

This interface represents a processing node which
<a href="#Spatialization">positions / spatializes</a> an incoming audio
stream in three-dimensional space. The spatialization is in relation
to the {{BaseAudioContext}}'s {{AudioListener}}
({{BaseAudioContext/listener}} attribute).

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-notes: Has <a>channelCount constraints</a>
    cc-mode: clamped-max
    cc-mode-notes: Has <a>channelCountMode constraints</a>
    cc-interp: speakers
    tail-time: Maybe
    tail-time-notes:  If the {{PannerNode/panningModel}} is set to "{{PanningModelType/HRTF}}", the node will produce non-silent output for silent input due to the inherent processing for head responses. Otherwise the tail-time is zero.
</pre>

The input of this node is either mono (1 channel) or stereo (2
channels) and cannot be increased. Connections from nodes with fewer
or more channels will be <a href="#channel-up-mixing-and-down-mixing">up-mixed or down-mixed
appropriately</a>.

If the node is [=actively processing=], the output of this node is
hard-coded to stereo (2 channels) and cannot be configured.  If the node
is not [=actively processing=], then the output is a single channel of
silence.

The {{PanningModelType}} enum determines which
spatialization algorithm will be used to position the audio in 3D
space. The default is "{{PanningModelType/equalpower}}".

<pre class="idl">
enum PanningModelType {
        "equalpower",
        "HRTF"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="PanningModelType">
    <caption>{{PanningModelType}} enumeration description</caption>
    <thead>
        <th>Enum value</th><th>Description</th>
    <tbody>
        <tr><td>"<dfn>equalpower</dfn>"
        <td>
            A simple and efficient spatialization algorithm using equal-power
            panning.

            Note: When this panning model is used, all the {{AudioParam}}s
            used to compute the output of this node are <a>a-rate</a>.

        <tr><td>"<dfn>HRTF</dfn>"
        <td>
            A higher quality spatialization algorithm using a convolution
            with measured impulse responses from human subjects. This panning
            method renders stereo output.

            Note:When this panning model is used, all the {{AudioParam}}s
            used to compute the output of this node are <a>k-rate</a>.
</table>
</div>

The <dfn>effective automation rate</dfn> for an {{AudioParam}} of a
{{PannerNode}} is determined by the {{PannerNode/panningModel}} and
{{AudioParam/automationRate}} of the {{AudioParam}}.  If the
{{PannerNode/panningModel}} is "{{PanningModelType/HRTF}}", the
[=effective automation rate=] is "{{AutomationRate/k-rate}}",
independent of the setting of the {{AudioParam/automationRate}}.
Otherwise the [=effective automation rate=] is the value of
{{AudioParam/automationRate}}.

The {{DistanceModelType}} enum determines which
algorithm will be used to reduce the volume of an audio source as it
moves away from the listener. The default is "{{DistanceModelType/inverse}}".

In the description of each distance model below, let \(d\) be the
distance between the listener and the panner; \(d_{ref}\) be the
value of the {{PannerNode/refDistance}} attribute; \(d_{max}\) be the
value of the {{PannerNode/maxDistance}} attribute; and \(f\) be the
value of the {{PannerNode/rolloffFactor}} attribute.

<pre class="idl">
enum DistanceModelType {
    "linear",
    "inverse",
    "exponential"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="DistanceModelType">
    <caption>{{DistanceModelType}} enumeration description</caption>
    <thead>
        <th>Enum value</th><th>Description</th>
    <tbody>
        <tr>
            <td>"<dfn>linear</dfn>"
            <td>
                A linear distance model which calculates <em>distanceGain</em>
                according to:

                <pre nohighlight>
                $$
                    1 - f\ \frac{\max\left[\min\left(d, d'_{max}\right), d'_{ref}\right] - d'_{ref}}{d'_{max} - d'_{ref}}
                $$
                </pre>

                where \(d'_{ref} = \min\left(d_{ref}, d_{max}\right)\) and \(d'_{max} =
                \max\left(d_{ref}, d_{max}\right)\). In the case where \(d'_{ref} =
                d'_{max}\), the value of the linear model is taken to be
                \(1-f\).

                Note that \(d\) is clamped to the interval \(\left[d'_{ref},\,
                d'_{max}\right]\).

        <tr>
            <td>"<dfn>inverse</dfn>"
            <td>
                An inverse distance model which calculates
                <em>distanceGain</em> according to:

                <pre nohighlight>
                $$
                    \frac{d_{ref}}{d_{ref} + f\ \left[\max\left(d, d_{ref}\right) - d_{ref}\right]}
                $$
                </pre>

                That is, \(d\) is clamped to the interval \(\left[d_{ref},\,
                \infty\right)\). If \(d_{ref} = 0\), the value of the inverse model
                is taken to be 0, independent of the value of \(d\) and \(f\).

        <tr>
            <td>"<dfn>exponential</dfn>"
            <td>
                An exponential distance model which calculates
                <em>distanceGain</em> according to:

                <pre nohighlight>
                $$
                    \left[\frac{\max\left(d, d_{ref}\right)}{d_{ref}}\right]^{-f}
                $$
                </pre>

                That is, \(d\) is clamped to the interval \(\left[d_{ref},\,
                \infty\right)\). If \(d_{ref} = 0\), the value of the exponential
                model is taken to be 0, independent of \(d\) and \(f\).
</table>
</div>

<pre class="idl">
[Exposed=Window]
interface PannerNode : AudioNode {
    constructor (BaseAudioContext context, optional PannerOptions options = {});
    attribute PanningModelType panningModel;
    readonly attribute AudioParam positionX;
    readonly attribute AudioParam positionY;
    readonly attribute AudioParam positionZ;
    readonly attribute AudioParam orientationX;
    readonly attribute AudioParam orientationY;
    readonly attribute AudioParam orientationZ;
    attribute DistanceModelType distanceModel;
    attribute double refDistance;
    attribute double maxDistance;
    attribute double rolloffFactor;
    attribute double coneInnerAngle;
    attribute double coneOuterAngle;
    attribute double coneOuterGain;
    undefined setPosition (float x, float y, float z);
    undefined setOrientation (float x, float y, float z);
};
</pre>

<h4 id="PannerNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="PannerNode">
    : <dfn>PannerNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="PannerNode/constructor()">
            context: The {{BaseAudioContext}} this new {{PannerNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{PannerNode}}.
        </pre>
</dl>

<h4 id="PannerNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="PannerNode">
    : <dfn>coneInnerAngle</dfn>
    ::
        A parameter for directional audio sources that is an angle, in
        degrees, inside of which there will be no volume reduction. The
        default value is 360. The behavior is undefined if the angle is
        outside the interval [0, 360].

    : <dfn>coneOuterAngle</dfn>
    ::
        A parameter for directional audio sources that is an angle, in
        degrees, outside of which the volume will be reduced to a
        constant value of {{PannerNode/coneOuterGain}}. The default
        value is 360. The behavior is undefined if the angle is outside
        the interval [0, 360].

    : <dfn>coneOuterGain</dfn>
    ::
        A parameter for directional audio sources that is the gain
        outside of the {{PannerNode/coneOuterAngle}}. The default
        value is 0. It is a linear value (not dB) in the range [0, 1]. <span class="synchronous">An
        {{InvalidStateError}} MUST be thrown if the parameter is
        outside this range.</span>

    : <dfn>distanceModel</dfn>
    ::
        Specifies the distance model used by this
        {{PannerNode}}. Defaults to
        "{{inverse}}".

    : <dfn>maxDistance</dfn>
    ::
        The maximum distance between source and listener, after which the
        volume will not be reduced any further. The default value is 10000.
                <span class="synchronous">A {{RangeError}} exception MUST be thrown if this
        is set to a non-positive value.</span>

    : <dfn>orientationX</dfn>
    ::
        Describes the \(x\)-component of the vector of the direction the
        audio source is pointing in 3D Cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 1
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>orientationY</dfn>
    ::
        Describes the \(y\)-component of the vector of the direction the
        audio source is pointing in 3D cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>orientationZ</dfn>
    ::
        Describes the \(z\)-component of the vector of the direction the
        audio source is pointing in 3D cartesian coordinate space.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>panningModel</dfn>
    ::
        Specifies the panning model used by this
        {{PannerNode}}. Defaults to
        "{{PanningModelType/equalpower}}".

    : <dfn>positionX</dfn>
    ::
        Sets the \(x\)-coordinate position of the audio source in a 3D
        Cartesian system.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>positionY</dfn>
    ::
        Sets the \(y\)-coordinate position of the audio source in a 3D
        Cartesian system.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>positionZ</dfn>
    ::
        Sets the \(z\)-coordinate position of the audio source in a 3D
        Cartesian system.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: <a>most-negative-single-float</a>
            min-notes: Approximately -3.4028235e38
            max: <a>most-positive-single-float</a>
            max-notes: Approximately 3.4028235e38
            rate: "{{AutomationRate/a-rate}}"
            rate-notes: Has [=automation rate constraints=]
        </pre>

    : <dfn>refDistance</dfn>
    ::
        A reference distance for reducing volume as source moves further
        from the listener. For distances less than this, the volume is not reduced. The default value is 1. <span class="synchronous">A
        {{RangeError}} exception MUST be thrown if this is set
        to a negative value.</span>

    : <dfn>rolloffFactor</dfn>
    ::
        Describes how quickly the volume is reduced as source moves
        away from listener. The default value is 1. <span class="synchronous">A
        {{RangeError}} exception MUST be thrown if this is set to
        a negative value.</span>

        The nominal range for the {{PannerNode/rolloffFactor}} specifies
        the minimum and maximum values the <code>rolloffFactor</code>
        can have. Values outside the range are clamped to lie within
        this range. The nominal range depends on the {{PannerNode/distanceModel}} as follows:

        <dl dfn-for="DistanceModelType">
            : "{{linear}}"
            :: The nominal range is \([0, 1]\).

            : "{{inverse}}"
            :: The nominal range is \([0, \infty)\).

            : "{{exponential}}"
            :: The nominal range is \([0, \infty)\).
        </dl>

        Note that the clamping happens as part of the
        processing of the distance computation.  The attribute
        reflects the value that was set and is not modified.
</dl>

<h4 id="PannerNode-methods">
Methods</h4>

<dl dfn-type=method dfn-for="PannerNode">
    : <dfn>setOrientation(x, y, z)</dfn>
    ::
        This method is DEPRECATED. It is equivalent to setting
        {{PannerNode/orientationX}}.{{AudioParam/value}},
        {{PannerNode/orientationY}}.{{AudioParam/value}},
        and {{PannerNode/orientationZ}}.{{AudioParam/value}}
        attribute directly, with the <code>x</code>, <code>y</code> and
        <code>z</code> parameters, respectively.

        <span class="synchronous">Consequently, if any of the {{PannerNode/orientationX}},
        {{PannerNode/orientationY}}, and {{PannerNode/orientationZ}} {{AudioParam}}s
        have an automation curve set using {{AudioParam/setValueCurveAtTime()}} at the time
        this method is called, a {{NotSupportedError}} MUST be
        thrown.</span>

        Describes which direction the audio source is pointing in the
        3D cartesian coordinate space. Depending on how directional the
        sound is (controlled by the <b>cone</b> attributes), a sound
        pointing away from the listener can be very quiet or completely
        silent.

        The <code>x, y, z</code> parameters represent a direction
        vector in 3D space.

        The default value is (1,0,0).

        <pre class=argumentdef for="PannerNode/setOrientation()">
            x:
            y:
            z:
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>

    : <dfn>setPosition(x, y, z)</dfn>
    ::
        This method is DEPRECATED. It is equivalent to setting
        {{PannerNode/positionX}}.{{AudioParam/value}},
        {{PannerNode/positionY}}.{{AudioParam/value}}, and
        {{PannerNode/positionZ}}.{{AudioParam/value}}
        attribute directly with the <code>x</code>, <code>y</code> and
        <code>z</code> parameters, respectively.

        <span class="synchronous">Consequently, if any of the {{PannerNode/positionX}}, {{PannerNode/positionY}},
        and {{PannerNode/positionZ}} {{AudioParam}}s have an automation
        curve set using {{AudioParam/setValueCurveAtTime()}} at the time
        this method is called, a {{NotSupportedError}} MUST be
        thrown.</span>

        Sets the position of the audio source relative to the
        {{BaseAudioContext/listener}} attribute. A 3D cartesian
        coordinate system is used.

        The <code>x, y, z</code> parameters represent the coordinates
        in 3D space.

        The default value is (0,0,0).

        <pre class=argumentdef for="PannerNode/setPosition()">
            x:
            y:
            z:
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>

<h4 dictionary id="PannerOptions">
{{PannerOptions}}</h4>

This specifies options for constructing a
{{PannerNode}}. All members are optional; if not
specified, the normal default is used in constructing the node.

<pre class="idl">
dictionary PannerOptions : AudioNodeOptions {
    PanningModelType panningModel = "equalpower";
    DistanceModelType distanceModel = "inverse";
    float positionX = 0;
    float positionY = 0;
    float positionZ = 0;
    float orientationX = 1;
    float orientationY = 0;
    float orientationZ = 0;
    double refDistance = 1;
    double maxDistance = 10000;
    double rolloffFactor = 1;
    double coneInnerAngle = 360;
    double coneOuterAngle = 360;
    double coneOuterGain = 0;
};
</pre>

<h5 id="dictionary-pannernode-members">
Dictionary {{PannerOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="PannerOptions">
    : <dfn>coneInnerAngle</dfn>
    :: The initial value for the {{PannerNode/coneInnerAngle}} attribute of the node.

    : <dfn>coneOuterAngle</dfn>
    ::  The initial value for the {{PannerNode/coneOuterAngle}} attribute of the node.

    : <dfn>coneOuterGain</dfn>
    :: The initial value for the {{PannerNode/coneOuterGain}} attribute of the node.

    : <dfn>distanceModel</dfn>
    :: The distance model to use for the node.

    : <dfn>maxDistance</dfn>
    :: The initial value for the {{PannerNode/maxDistance}} attribute of the node.

    : <dfn>orientationX</dfn>
    :: The initial \(x\)-component value for the {{PannerNode/orientationX}} AudioParam.

    : <dfn>orientationY</dfn>
    :: The initial \(y\)-component value for the {{PannerNode/orientationY}} AudioParam.

    : <dfn>orientationZ</dfn>
    :: The initial \(z\)-component value for the {{PannerNode/orientationZ}} AudioParam.

    : <dfn>panningModel</dfn>
    :: The panning model to use for the node.

    : <dfn>positionX</dfn>
    :: The initial \(x\)-coordinate value for the {{PannerNode/positionX}} AudioParam.

    : <dfn>positionY</dfn>
    :: The initial \(y\)-coordinate value for the {{PannerNode/positionY}} AudioParam.

    : <dfn>positionZ</dfn>
    :: The initial \(z\)-coordinate  value for the {{PannerNode/positionZ}} AudioParam.

    : <dfn>refDistance</dfn>
    :: The initial value for the {{PannerNode/refDistance}} attribute of the node.

    : <dfn>rolloffFactor</dfn>
    :: The initial value for the {{PannerNode/rolloffFactor}} attribute of the node.
</dl>

<h4 id="panner-channel-limitations">
Channel Limitations</h4>

The set of <a href="#panner-channel-limitations">channel
limitations</a> for {{StereoPannerNode}} also apply
to {{PannerNode}}.

<!-- Big Text: Periodic -->

<h3 interface lt="PeriodicWave" id="PeriodicWave">
The {{PeriodicWave}} Interface</h3>

{{PeriodicWave}} represents an arbitrary periodic waveform to be used
with an {{OscillatorNode}}.

A <a>conforming implementation</a> MUST support {{PeriodicWave}}
up to at least 8192 elements.

<pre class="idl">
[Exposed=Window]
interface PeriodicWave {
    constructor (BaseAudioContext context, optional PeriodicWaveOptions options = {});
};
</pre>

<h4 id="PeriodicWave-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="PeriodicWave">
    : <dfn>PeriodicWave(context, options)</dfn>
    ::
        <div algorithm="construct periodic wave">
            1. Let <var>p</var> be a new {{PeriodicWave}} object. Let <dfn attribute for="PeriodicWave">\[[real]]</dfn> and <dfn attribute for="PeriodicWave">\[[imag]]</dfn> be two internal slots of type {{Float32Array}}, and let <dfn attribute for="PeriodicWave">\[[normalize]]</dfn> be an internal slot.

            1. Process {{PeriodicWave/constructor(context, options)/options!!argument}} according to one of the following cases:
                1. If both {{PeriodicWaveOptions/real|options.real}} and {{PeriodicWaveOptions/imag|options.imag}} are present
                    1. <span class="synchronous">If the lengths of {{PeriodicWaveOptions/real|options.real}} and {{PeriodicWaveOptions/imag|options.imag}} are different or if either length is less than 2, throw an {{IndexSizeError}} and abort this algorithm.</span>
                    1. Set {{[[real]]}} and {{[[imag]]}} to new arrays with the same length as {{PeriodicWaveOptions/real|options.real}}.
                    1. Copy all elements from {{PeriodicWaveOptions/real|options.real}} to {{[[real]]}} and {{PeriodicWaveOptions/imag|options.imag}} to {{[[imag]]}}.
                1. If only {{PeriodicWaveOptions/real|options.real}} is present
                    1. <span class="synchronous">If length of {{PeriodicWaveOptions/real|options.real}} is less than 2, throw an {{IndexSizeError}} and abort this algorithm.</span>
                    1. Set {{[[real]]}} and {{[[imag]]}} to arrays with the same length as {{PeriodicWaveOptions/real|options.real}}.
                    1. Copy {{PeriodicWaveOptions/real|options.real}} to {{[[real]]}} and set {{[[imag]]}} to all zeros.
                1. If only {{PeriodicWaveOptions/imag|options.imag}} is present
                    1. <span class="synchronous">If length of {{PeriodicWaveOptions/imag|options.imag}} is less than 2, throw an {{IndexSizeError}} and abort this algorithm.</span>
                    1. Set {{[[real]]}} and {{[[imag]]}} to arrays with the same length as {{PeriodicWaveOptions/real|options.imag}}.
                    1. Copy {{PeriodicWaveOptions/imag|options.imag}} to {{[[imag]]}} and set {{[[real]]}} to all zeros.
                1. Otherwise
                    1. Set {{[[real]]}} and {{[[imag]]}} to zero-filled arrays of length 2.
                    1. Set element at index 1 of {{[[imag]]}} to 1.

                    Note: When setting this {{PeriodicWave}} on an {{OscillatorNode}}, this is equivalent to using the built-in type "{{OscillatorType/sine}}".
            1. Set element at index 0 of both {{[[real]]}} and {{[[imag]]}} to 0.  (This sets the DC component to 0.)
    
            5. Initialize {{[[normalize]]}} to the inverse of the
                {{PeriodicWaveConstraints/disableNormalization}} attribute of the
                {{PeriodicWaveConstraints}} on the
                {{PeriodicWaveOptions}}.

            6. Return <var>p</var>.
        </div>

        <pre class=argumentdef for="PeriodicWave/constructor()">
            context: The {{BaseAudioContext}} this new {{PeriodicWave}} will be <a href="#associated">associated</a> with. Unlike {{AudioBuffer}}, {{PeriodicWave}}s can't be shared accross {{AudioContext}}s or {{OfflineAudioContext}}s. It is associated with a particular {{BaseAudioContext}}.
            options: Optional initial parameter value for this {{PeriodicWave}}.
        </pre>
</dl>

<h4 dictionary id="PeriodicWaveConstraints">
{{PeriodicWaveConstraints}}</h4>

The {{PeriodicWaveConstraints}} dictionary is used to
specify how the waveform is [[#waveform-normalization|normalized]].

<pre class="idl">
dictionary PeriodicWaveConstraints {
    boolean disableNormalization = false;
};
</pre>

<h5 id="dictionary-periodicwaveconstraints-members">
Dictionary {{PeriodicWaveConstraints}} Members</h5>

<dl dfn-type=dict-member dfn-for="PeriodicWaveConstraints">
    : <dfn>disableNormalization</dfn>
    ::
        Controls whether the periodic wave is normalized or not. If
        `true`, the waveform is not normalized; otherwise,
        the waveform is normalized.
</dl>

<h4 dictionary id="PeriodicWaveOptions">
{{PeriodicWaveOptions}}</h4>

The {{PeriodicWaveOptions}} dictionary is used to specify
how the waveform is constructed. If only one of {{PeriodicWaveOptions/real}}
or {{PeriodicWaveOptions/imag}} is specified. The other is treated as if it
were an array of all zeroes of the same length, as specified below
in <a href="#dictionary-periodicwaveoptions-members">description of
the dictionary members</a>. If neither is given, a
{{PeriodicWave}} is created that MUST be equivalent
to an {{OscillatorNode}} with
{{OscillatorNode/type}} "{{OscillatorType/sine}}". If
both are given, the sequences must have the same length; otherwise
an <span class="synchronous">error of type
{{NotSupportedError}} MUST be thrown</span>.

<xmp class="idl">
dictionary PeriodicWaveOptions : PeriodicWaveConstraints {
    sequence<float> real;
    sequence<float> imag;
};
</xmp>

<h5 id="dictionary-periodicwaveoptions-members">
Dictionary {{PeriodicWaveOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="PeriodicWaveOptions">
    : <dfn>imag</dfn>
    ::
        The {{PeriodicWaveOptions/imag}} parameter represents an array of
        <code>sine</code> terms. The first element (index 0) does not
        exist in the Fourier series.  The second element
        (index 1) represents the fundamental frequency.  The
        third represents the first overtone and so on.

    : <dfn>real</dfn>
    ::
        The {{PeriodicWaveOptions/real}} parameter represents an array of
        <code>cosine</code> terms. The first element (index 0) is the
        DC-offset of the periodic waveform. The second element
        (index 1) represents the fundamental frequency.  The
        third represents the first overtone and so on.
</dl>

<h4 id="waveform-generation">
Waveform Generation</h4>

The {{BaseAudioContext/createPeriodicWave()}}
method takes two arrays to specify the Fourier coefficients of the
{{PeriodicWave}}. Let \(a\) and \(b\) represent the {{[[real]]}} and {{[[imag]]}}
arrays of length \(L\), respectively. Then the basic time-domain waveform,
\(x(t)\), can be computed using:

<pre nohighlight>
$$
    x(t) = \sum_{k=1}^{L-1} \left[a[k]\cos2\pi k t + b[k]\sin2\pi k t\right]
$$
</pre>

This is the basic (unnormalized) waveform.


<h4 id="waveform-normalization">
Waveform Normalization</h4>

If the internal slot {{[[normalize]]}} of this
{{PeriodicWave}} is `true` (the default), the
waveform defined in the previous section is normalized so that the
maximum value is 1. The normalization is done as follows.

Let

<pre nohighlight>
$$
    \tilde{x}(n) = \sum_{k=1}^{L-1} \left(a[k]\cos\frac{2\pi k n}{N} + b[k]\sin\frac{2\pi k n}{N}\right)
$$
</pre>

where \(N\) is a power of two. (Note: \(\tilde{x}(n)\) can
conveniently be computed using an inverse FFT.) The fixed
normalization factor \(f\) is computed as follows.

<pre nohighlight>
$$
    f = \max_{n = 0, \ldots, N - 1} |\tilde{x}(n)|
$$
</pre>

Thus, the actual normalized waveform \(\hat{x}(n)\) is:

<pre nohighlight>
$$
    \hat{x}(n) = \frac{\tilde{x}(n)}{f}
$$
</pre>

This fixed normalization factor MUST be applied to all generated
waveforms.

<h4 id="oscillator-coefficients">
Oscillator Coefficients</h4>

The builtin oscillator types are created using {{PeriodicWave}}
objects. For completeness the coefficients for the {{PeriodicWave}} for
each of the builtin oscillator types is given here. This is useful
if a builtin type is desired but without the default normalization.

In the following descriptions, let \(a\) be the array of real
coefficients and \(b\) be the array of imaginary coefficients for
{{BaseAudioContext/createPeriodicWave()}}. In
all cases \(a[n] = 0\) for all \(n\) because the waveforms are odd
functions. Also, \(b[0] = 0\) in all cases. Hence, only \(b[n]\)
for \(n \ge 1\) is specified below.

<dl link-for="OscillatorType">
    : "{{sine}}"
    ::
        <pre nohighlight>
        $$
            b[n] = \begin{cases}
                             1 &amp; \mbox{for } n = 1 \\
                             0 &amp; \mbox{otherwise}
                         \end{cases}
        $$
        </pre>

    : "{{square}}"
    ::
        <pre nohighlight>
        $$
            b[n] = \frac{2}{n\pi}\left[1 - (-1)^n\right]
        $$
        </pre>

    : "{{sawtooth}}"
    ::
        <pre nohighlight>
        $$
            b[n] = (-1)^{n+1} \dfrac{2}{n\pi}
        $$
        </pre>

    : "{{triangle}}"
    ::
        <pre nohighlight>
        $$
            b[n] = \frac{8\sin\dfrac{n\pi}{2}}{(\pi n)^2}
        $$
        </pre>
</dl>


<!-- Big Text: Script -->
<!-- Big Text: Processor -->

<h3 interface lt="ScriptProcessorNode" id="ScriptProcessorNode">
The {{ScriptProcessorNode}} Interface - DEPRECATED</h3>

This interface is an {{AudioNode}} which can
generate, process, or analyse audio directly using a script. This
node type is deprecated, to be replaced by the
{{AudioWorkletNode}}; this text is only here for informative
purposes until implementations remove this node type.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: {{BaseAudioContext/createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels)/numberOfInputChannels}}
    cc-notes: This is the number of channels specified when constructing this node. There are <a>channelCount constraints</a>.
    cc-mode: explicit
    cc-mode-notes:  Has <a>channelCountMode constraints</a>
    cc-interp: speakers
    tail-time: No
</pre>

The {{ScriptProcessorNode}} is constructed with a
{{BaseAudioContext/createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels)/bufferSize}} which MUST be one of the following values: 256,
512, 1024, 2048, 4096, 8192, 16384. This value controls how
frequently the {{ScriptProcessorNode/audioprocess}} event is dispatched and how
many sample-frames need to be processed each call. {{ScriptProcessorNode/audioprocess}} events are only
dispatched if the {{ScriptProcessorNode}} has at
least one input or one output connected. Lower numbers for
{{ScriptProcessorNode/bufferSize}} will result in
a lower (better) <a href="#latency">latency</a>. Higher numbers will
be necessary to avoid audio breakup and <a href="#audio-glitching">glitches</a>. This value will be picked by the
implementation if the bufferSize argument to
{{createScriptProcessor()}} is not passed in, or is set to 0.

{{numberOfInputChannels}} and {{numberOfOutputChannels}}
determine the number of input and output channels. It is invalid for
both {{numberOfInputChannels}} and {{numberOfOutputChannels}}
to be zero.

<pre class="idl">
[Exposed=Window]
interface ScriptProcessorNode : AudioNode {
    attribute EventHandler onaudioprocess;
    readonly attribute long bufferSize;
};
</pre>

<h4 id="ScriptProcessorNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="ScriptProcessorNode">
    : <dfn>bufferSize</dfn>
    ::
        The size of the buffer (in sample-frames) which needs to be
        processed each time {{ScriptProcessorNode/audioprocess}} is fired.
        Legal values are (256, 512, 1024, 2048, 4096, 8192, 16384).

    : <dfn>onaudioprocess</dfn>
    ::
        A property used to set an [=event handler=] for the
        <dfn event>audioprocess</dfn> event type that is dispatched to
        {{ScriptProcessorNode}} node types. The event dispatched to the event
        handler uses the {{AudioProcessingEvent}} interface.
</dl>


<!-- Big Text: Stereo -->
<!-- Big Text: Panner -->

<h3 interface lt="StereoPannerNode" id="stereopannernode">
The {{StereoPannerNode}} Interface</h3>

This interface represents a processing node which positions an
incoming audio stream in a stereo image using <a href="#stereopanner-algorithm">a low-cost panning
algorithm</a>. This panning effect is common in positioning audio
components in a stereo stream.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-notes: Has <a>channelCount constraints</a>
    cc-mode: clamped-max
    cc-mode-notes: Has <a>channelCountMode constraints</a>
    cc-interp: speakers
    tail-time: No
</pre>

The input of this node is stereo (2 channels) and cannot be
increased. Connections from nodes with fewer or more channels will be
<a href="#channel-up-mixing-and-down-mixing">up-mixed or down-mixed
appropriately</a>.

The output of this node is hard-coded to stereo (2 channels) and
cannot be configured.

<pre class="idl">
[Exposed=Window]
interface StereoPannerNode : AudioNode {
    constructor (BaseAudioContext context, optional StereoPannerOptions options = {});
    readonly attribute AudioParam pan;
};
</pre>

<h4 id="StereoPannerNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="StereoPannerNode">
    : <dfn>StereoPannerNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        <pre class=argumentdef for="StereoPannerNode/constructor()">
            context: The {{BaseAudioContext}} this new {{StereoPannerNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{StereoPannerNode}}.
        </pre>
</dl>

<h4 id="StereoPannerNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="StereoPannerNode">
    : <dfn>pan</dfn>
    ::
        The position of the input in the output's stereo image. -1
        represents full left, +1 represents full right.

        <pre class=include>
        path: audioparam.include
        macros:
            default: 0
            min: -1
            max: 1
            rate: "{{AutomationRate/a-rate}}"
        </pre>
</dl>

<h4 dictionary id="StereoPannerOptions">
{{StereoPannerOptions}}</h4>

This specifies the options to use in constructing a
{{StereoPannerNode}}. All members are optional; if
not specified, the normal default is used in constructing the node.

<pre class="idl">
dictionary StereoPannerOptions : AudioNodeOptions {
    float pan = 0;
};
</pre>

<h5 id="dictionary-stereopanneroptions-members">
Dictionary {{StereoPannerOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="StereoPannerOptions">
    : <dfn>pan</dfn>
    :: The initial value for the {{StereoPannerNode/pan}} AudioParam.
</dl>

<h4 id="StereoPanner-channel-limitations">
Channel Limitations</h4>

Because its processing is constrained by the above definitions,
{{StereoPannerNode}} is limited to mixing no more
than 2 channels of audio, and producing exactly 2 channels. It is
possible to use a {{ChannelSplitterNode}},
intermediate processing by a subgraph of
{{GainNode}}s and/or other nodes, and recombination
via a {{ChannelMergerNode}} to realize arbitrary
approaches to panning and mixing.


<!-- Big Text: Wave -->
<!-- Big Text: Shaper -->

<h3 interface lt="WaveShaperNode" id="WaveShaperNode">
The {{WaveShaperNode}} Interface</h3>

{{WaveShaperNode}} is an
{{AudioNode}} processor implementing non-linear
distortion effects.

Non-linear waveshaping distortion is commonly used for both subtle
non-linear warming, or more obvious distortion effects. Arbitrary
non-linear shaping curves may be specified.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: Maybe
    tail-time-notes: There is a <a>tail-time</a> only if the {{WaveShaperNode/oversample}} attribute is set to "{{OverSampleType/2x}}" or "{{OverSampleType/4x}}". The actual duration of this <a>tail-time</a> depends on the implementation.
</pre>

The number of channels of the output always equals the number of
channels of the input.

<pre class="idl">
enum OverSampleType {
    "none",
    "2x",
    "4x"
};
</pre>

<div class="enum-description">
<table class="simple" dfn-type=enum-value dfn-for="OverSampleType">
    <caption>{{OverSampleType}} enumeration description</caption>
    <thead>
        <th>Enum value</th><th>Description</th>
    <tbody>
        <tr><td>"<dfn>none</dfn>"
            <td>Don't oversample

        <tr><td>"<dfn>2x</dfn>"
            <td>Oversample two times

        <tr><td>"<dfn>4x</dfn>"
            <td>Oversample four times
</table>
</div>

<pre class="idl">
[Exposed=Window]
interface WaveShaperNode : AudioNode {
    constructor (BaseAudioContext context, optional WaveShaperOptions options = {});
    attribute Float32Array? curve;
    attribute OverSampleType oversample;
};
</pre>

<h4 id="WaveShaperNode-constructors">
Constructors</h4>

<dl dfn-type=constructor dfn-for="WaveShaperNode">
    : <dfn>WaveShaperNode(context, options)</dfn>
    ::

        <pre class=include>
            path: audionode-init.include
        </pre>

        Also, let <dfn attribute for="WaveShaperNode">[[curve set]]</dfn> be an internal
        slot of this {{WaveShaperNode}}.  Initialize this slot to <code>false</code>.  If
        {{WaveShaperNode/constructor(context, options)/options}} is given and specifies a
        {{WaveShaperOptions/curve}}, set {{[[curve set]]}} to <code>true</code>.

        <pre class=argumentdef for="WaveShaperNode/constructor()">
            context: The {{BaseAudioContext}} this new {{WaveShaperNode}} will be <a href="#associated">associated</a> with.
            options: Optional initial parameter value for this {{WaveShaperNode}}.
        </pre>
</dl>

<h4 id="WaveShaperNode-attributes">
Attributes</h4>

<dl dfn-type=attribute dfn-for="WaveShaperNode">
    : <dfn>curve</dfn>
    ::
        The shaping curve used for the waveshaping effect. The input
        signal is nominally within the range [-1, 1]. Each input sample
        within this range will index into the shaping curve, with a
        signal level of zero corresponding to the center value of the
        curve array if there are an odd number of entries, or
        interpolated between the two centermost values if there are an
        even number of entries in the array. Any sample value less than
        -1 will correspond to the first value in the curve array. Any
        sample value greater than +1 will correspond to the last value
        in the curve array.

        The implementation MUST perform linear interpolation between
        adjacent points in the curve. Initially the curve attribute is
        null, which means that the WaveShaperNode will pass its input
        to its output without modification.

        Values of the curve are spread with equal spacing in the [-1;
        1] range. This means that a {{WaveShaperNode/curve}} with a
        even number of value will not have a value for a signal at
        zero, and a {{WaveShaperNode/curve}} with an odd number of
        value will have a value for a signal at zero.  The
        output is determined by the following algorithm.

        <div algorithm="wave-shaper-curve">
            1. Let \(x\) be the input sample, \(y\) be the
                corresponding output of the node,
                \(c_k\) be the \(k\)'th element of the
                {{WaveShaperNode/curve}}, and \(N\) be
                the length of the
                {{WaveShaperNode/curve}}.

            1. Let
                <pre nohighlight>
                $$
                    \begin{align*}
                    v &= \frac{N-1}{2}(x + 1) \\
                    k &= \lfloor v \rfloor \\
                    f &= v - k
                    \end{align*}
                $$
                </pre>
            1. Then
                <pre nohighlight>
                $$
                    \begin{align*}
                    y &=
                        \begin{cases}
                        c_0 & v \lt 0 \\
                        c_{N-1} & v \ge N - 1 \\
                        (1-f)\,c_k + fc_{k+1} & \mathrm{otherwise}
                        \end{cases}
                    \end{align*}
                $$
                </pre>
        </div>

        <span class="synchronous">A {{InvalidStateError}} MUST be thrown if this
        attribute is set with a {{Float32Array}} that has a
        <code>length</code> less than 2.</span>

        When this attribute is set, an internal copy of the curve is
        created by the {{WaveShaperNode}}. Subsequent
        modifications of the contents of the array used to set the
        attribute therefore have no effect.

        <div algorithm="WaveShaperNode.curve">
            To set the {{WaveShaperNode/curve}} attribute, execute these steps:

            1. Let <var>new curve</var> be a {{Float32Array}} to be assigned to {{WaveShaperNode/curve}} or <code>null</code>.
                .

            2. If <var>new curve</var> is not <code>null</code> and
                {{WaveShaperNode/[[curve set]]}} is true, throw an
                {{InvalidStateError}} and abort these steps.

            3. If <var>new curve</var> is not <code>null</code>, set
                {{WaveShaperNode/[[curve set]]}} to true.

            4. Assign <var>new curve</var> to the {{WaveShaperNode/curve}}
                attribute.
        </div>

        Note: The use of a curve that produces a non-zero
        output value for zero input value will cause this node
        to produce a DC signal even if there are no inputs
        connected to this node. This will persist until the
        node is disconnected from downstream nodes.

    : <dfn>oversample</dfn>
    ::
        Specifies what type of oversampling (if any) should be used
        when applying the shaping curve. The default value is "{{OverSampleType/none}}",
        meaning the curve will be applied directly to the input
        samples. A value of "{{2x}}" or "{{4x}}" can improve the quality of the
        processing by avoiding some aliasing, with the "{{4x}}" value
        yielding the highest quality. For some applications, it's
        better to use no oversampling in order to get a very precise
        shaping curve.


        <div algorithm="oversample">
            A value of "{{2x}}" or "{{4x}}" means that the following steps MUST be
            performed:

            1. Up-sample the input samples to 2x or 4x the sample-rate of
                the {{AudioContext}}. Thus for each <a>render
                quantum</a>, generate twice (for 2x) or four times (for 4x) samples.

            2. Apply the shaping curve.

            3. Down-sample the result back to the sample-rate of the
                {{AudioContext}}. Thus taking the previously processed samples
                processed samples, generating a single render quantum worth of
                samples as the final result.
        </div>

        The exact up-sampling and down-sampling filters are not
        specified, and can be tuned for sound quality (low aliasing,
        etc.), low latency, or performance.

        Note: Use of oversampling introduces some degree of audio processing
        latency due to the up-sampling and down-sampling filters. The
        amount of this latency can vary from one implementation to
        another.
</dl>

<h4 dictionary id="WaveShaperOptions">
{{WaveShaperOptions}}</h4>

This specifies the options for constructing a
{{WaveShaperNode}}. All members are optional; if
not specified, the normal default is used in constructing the node.

<xmp class="idl">
dictionary WaveShaperOptions : AudioNodeOptions {
    sequence<float> curve;
    OverSampleType oversample = "none";
};
</xmp>

<h5 id="dictionary-waveshaperoptions-members">
Dictionary {{WaveShaperOptions}} Members</h5>

<dl dfn-type=dict-member dfn-for="WaveShaperOptions">
    : <dfn>curve</dfn>
    :: The shaping curve for the waveshaping effect.

    : <dfn>oversample</dfn>
    :: The type of oversampling to use for the shaping curve.
</dl>


<!-- Big Text: AudioWorklet -->

<h3 interface lt="AudioWorklet" id="AudioWorklet">
The {{AudioWorklet}} Interface</h3>

<pre class="idl">
[Exposed=Window, SecureContext]
interface AudioWorklet : Worklet {
  readonly attribute MessagePort port;
};
</pre>

<h4 id="AudioWorklet-attributes">Attributes</h4>

<dl dfn-type=attribute dfn-for="AudioWorklet">
    : <dfn>port</dfn>
    ::
        A {{MessagePort}} connected to the port on the
        {{AudioWorkletGlobalScope}}.

        Note: Authors that register an event listener on the
        <code>"message"</code> event of this {{AudioWorklet/port}} should
        call {{MessagePort/close}} on either end of the {{MessageChannel}}
        (either in the {{AudioWorklet}} or the {{AudioWorkletGlobalScope}}
        side) to allow for resources to be
        [[html#ports-and-garbage-collection|collected]].
</dl>

<h4 id="AudioWorklet-concepts">
Concepts</h4>

The {{AudioWorklet}} object allows developers to supply scripts
(such as JavaScript or WebAssembly code) to process audio on the
<a>rendering thread</a>, supporting custom {{AudioNode}}s. This
processing mechanism ensures synchronous execution of the
script code with other built-in {{AudioNode}}s in the audio
graph.

An associated pair of objects MUST be defined in order to realize
this mechanism: {{AudioWorkletNode}} and
{{AudioWorkletProcessor}}. The former represents the interface
for the main global scope similar to other {{AudioNode}}
objects, and the latter implements the internal audio processing
within a special scope named {{AudioWorkletGlobalScope}}.

<figure>
    <img alt="AudioWorklet concept" src="images/audioworklet-concept.png" width="756" height="144">
    <figcaption>
        {{AudioWorkletNode}} and
        {{AudioWorkletProcessor}}
    </figcaption>
</figure>

Each {{BaseAudioContext}} possesses exactly one
{{AudioWorklet}}.

The {{AudioWorklet}}'s <a>worklet global scope type</a> is
{{AudioWorkletGlobalScope}}.

The {{AudioWorklet}}'s <a>worklet destination type</a> is
<code>"audioworklet"</code>.

Importing a script via the {{addModule()|addModule(moduleUrl)}}
method registers class definitions of {{AudioWorkletProcessor}}
under the {{AudioWorkletGlobalScope}}. There are two internal
storage areas for the imported class constructor and the active
instances created from the constructor.

{{AudioWorklet}} has one internal slot:

- <dfn>node name to parameter descriptor map</dfn> which is a map containing
    an identical set of string keys from <a>node name to processor
    constructor map</a> that are associated with the matching
    <a>parameterDescriptors</a> values. This internal storage is
    populated as a consequence of calling the {{registerProcessor()}}
    method in the <a>rendering thread</a>. The population is guaranteed
    to complete prior to the resolution of the promise returned by
    {{addModule()}} on a context's {{BaseAudioContext/audioWorklet}}.

<pre class="example" highlight="js" title="Registering an AudioWorkletProcessor class definition">
// bypass-processor.js script file, runs on AudioWorkletGlobalScope
class BypassProcessor extends AudioWorkletProcessor {
    process (inputs, outputs) {
        // Single input, single channel.
        const input = inputs[0];
        const output = outputs[0];
        output[0].set(input[0]);

        // Process only while there are active inputs.
        return false;
    }
};

registerProcessor('bypass-processor', BypassProcessor);
</pre>

<pre class="example" highlight="js" title="Importing a script and creating AudioWorkletNode">
// The main global scope
const context = new AudioContext();
context.audioWorklet.addModule('bypass-processor.js').then(() =&gt; {
    const bypassNode = new AudioWorkletNode(context, 'bypass-processor');
});
</pre>

At the instantiation of {{AudioWorkletNode}} in the main global
scope, the counterpart {{AudioWorkletProcessor}} will also be
created in {{AudioWorkletGlobalScope}}. These two objects
communicate via the asynchronous message passing described in
[[#processing-model]].

<h4 interface lt="AudioWorkletGlobalScope" id="AudioWorkletGlobalScope">
The {{AudioWorkletGlobalScope}} Interface</h4>

This special execution context is designed to enable the
generation, processing, and analysis of audio data directly using a
script in the audio <a>rendering thread</a>. The user-supplied
script code is evaluated in this scope to define one or more
{{AudioWorkletProcessor}} subclasses, which in turn are used to
instantiate {{AudioWorkletProcessor}}s, in a 1:1 association
with {{AudioWorkletNode}}s in the main scope.

Exactly one {{AudioWorkletGlobalScope}} exists for each
{{AudioContext}} that contains one or more
{{AudioWorkletNode}}s. The running of imported scripts is
performed by the UA as defined in [[!HTML]]. Overriding the default
specified in [[!HTML]], {{AudioWorkletGlobalScope}}s must not be
[=terminate a worklet global scope|terminated=] arbitrarily by the user
agent.

An {{AudioWorkletGlobalScope}} has the following internal slots:

- <dfn>node name to processor constructor map</dfn> which is a map
    that stores key-value pairs of
    <em>processor name</em> →
    <em>{{AudioWorkletProcessorConstructor}}</em> instance.
    Initially this map is empty and populated when the
    {{registerProcessor()}} method is called.
- <dfn>pending processor construction data</dfn> stores temporary data
    generated by the {{AudioWorkletNode}} constructor for the
    instantiation of the corresponding {{AudioWorkletProcessor}}. The
    [=pending processor construction data=] contains the following items:
    - <dfn for="pending processor construction data">node reference</dfn>
        which is initially empty. This storage is for an
        {{AudioWorkletNode}} reference that is transferred from the
        {{AudioWorkletNode}} constructor.
    - <dfn for="pending processor construction data">transferred port</dfn>
        which is initially empty. This storage is for a deserialized
        {{MessagePort}} that is transferred from the
        {{AudioWorkletNode}} constructor.

Note: The {{AudioWorkletGlobalScope}} may also contain any other data
and code to be shared by these instances. As an example, multiple
processors might share an ArrayBuffer defining a wavetable or an
impulse response.

Note: An {{AudioWorkletGlobalScope}} is associated with a single
{{BaseAudioContext}}, and with a single audio rendering thread
for that context. This prevents data races from occurring in global
scope code running within concurrent threads.

<pre class="idl">
callback AudioWorkletProcessorConstructor = AudioWorkletProcessor (object options);

[Global=(Worklet, AudioWorklet), Exposed=AudioWorklet]
interface AudioWorkletGlobalScope : WorkletGlobalScope {
    undefined registerProcessor (DOMString name,
                                               AudioWorkletProcessorConstructor processorCtor);
    readonly attribute unsigned long long currentFrame;
    readonly attribute double currentTime;
    readonly attribute float sampleRate;
    readonly attribute unsigned long renderQuantumSize;
    readonly attribute MessagePort port;
};
</pre>

<h5 id="AudioWorkletGlobalScope-attributes">
Attributes</h5>

<dl dfn-type=attribute dfn-for="AudioWorkletGlobalScope">
    : <dfn>currentFrame</dfn>
    ::
        The current frame of the block of audio being
        processed. This must be equal to the value of the
        {{[[current frame]]}} internal slot of the
        {{BaseAudioContext}}.

    : <dfn>currentTime</dfn>
    ::
        The context time of the block of audio being processed. This must be
        equal to the value of {{BaseAudioContext}}'s
        {{BaseAudioContext/currentTime}} attribute.

    : <dfn>sampleRate</dfn>
    ::
        The sample rate of the associated {{BaseAudioContext}}.

    : <dfn>renderQuantumSize</dfn>
    ::
        The value of the private slot <a>render quantum size</a> of the associated
        {{BaseAudioContext}}.

    : <dfn>port</dfn>
    ::
        A {{MessagePort}} connected to the port on the {{AudioWorklet}}.

        Note: Authors that register an event listener on the <code>"message"</code>
        event of this {{AudioWorkletGlobalScope/port}} should call
        {{MessagePort/close}} on either end of the {{MessageChannel}} (either
        in the {{AudioWorklet}} or the {{AudioWorkletGlobalScope}} side) to
        allow for resources to be
        [[html#ports-and-garbage-collection|collected]].
</dl>

<h5 id="AudioWorkletGlobalScope-methods">
Methods</h5>

<dl dfn-type=method dfn-for="AudioWorkletGlobalScope">
    : <dfn>registerProcessor(name, processorCtor)</dfn>
    ::
        Registers a class constructor derived from
        {{AudioWorkletProcessor}}.

        <div algorithm="AudioWorkletGlobalScope.registerProcess(name, processorCtr)">
            When the {{AudioWorkletGlobalScope/registerProcessor(name, processorCtor)}}
            method is called, perform the following steps. If an
            exception is thrown in any step, abort the remaining
            steps.

            1. If <var>name</var> is an empty string,
                <span class="synchronous">throw a
                {{NotSupportedError}}</span>.

            1. If <var>name</var> already exists as a key in the
                <a>node name to processor constructor map</a>,
                <span class="synchronous">throw a
                {{NotSupportedError}}</span>.

            1. If the result of
                <code><a href="https://tc39.es/ecma262#sec-isconstructor">IsConstructor</a>(argument=<var>processorCtor</var>)</code>
                is <code>false</code>,
                <span class="synchronous">throw a {{TypeError}}
                </span>.

            1. Let <code><em>prototype</em></code> be the result of
                <code><a href="https://tc39.es/ecma262#sec-get-o-p">
                Get</a>(O=<i>processorCtor</i>,
                P="prototype")</code>.

            1. If the result of
                <code><a href="https://tc39.es/ecma262#sec-ecmascript-data-types-and-values">Type</a>(argument=<i>prototype</i>)</code>
                is not <code>Object</code>,
                <span class="synchronous">throw a {{TypeError}}
                </span>.

            1. Let <var>parameterDescriptorsValue</var> be the
                result of
                <code><a href="https://tc39.es/ecma262#sec-get-o-p">Get</a>(O=<i>processorCtor</i>, P="parameterDescriptors")</code>.

            1. If <var>parameterDescriptorsValue</var> is not {{undefined}},
                execute the following steps:

                1. Let <var>parameterDescriptorSequence</var>
                    be the result of
                    <a href="https://webidl.spec.whatwg.org/#es-to-sequence">
                    the conversion</a> from
                    <var>parameterDescriptorsValue</var>
                    to an IDL value of type
                    <code>sequence&lt;AudioParamDescriptor&gt;</code>.

                1. Let <var>paramNames</var> be an empty Array.

                1. <div id="steps-parameterDescriptorSequence"></div>
                    For each <var>descriptor</var> of
                    <var>parameterDescriptorSequence</var>:
                    1. Let <var>paramName</var> be the value of
                        the member {{AudioParamDescriptor/name}}
                        in <var>descriptor</var>. <span class="synchronous">Throw
                        a {{NotSupportedError}}</span> if
                        <var>paramNames</var> already
                        contains <var>paramName</var> value.

                    1. Append <var>paramName</var> to
                        the <var>paramNames</var> array.

                    1. Let <var>defaultValue</var> be the value of
                        the member
                        {{AudioParamDescriptor/defaultValue}}
                        in <var>descriptor</var>.

                    1. Let <var>minValue</var> be the value of
                        the member
                        {{AudioParamDescriptor/minValue}}
                        in <var>descriptor</var>.

                    1. Let <var>maxValue</var> be the value of
                        the member
                        {{AudioParamDescriptor/maxValue}}
                        in <var>descriptor</var>.

                    1. If the expresstion
                        <var>minValue</var> &lt;=
                        <var>defaultValue</var> &lt;=
                        <var>maxValue</var> is false,
                        <span class="synchronous">throw
                        an {{InvalidStateError}}</span>.

            1. Append the key-value pair <var>name</var> →
                <var>processorCtor</var> to
                <a>node name to processor constructor map</a>
                of the associated {{AudioWorkletGlobalScope}}.

            1. <a href="https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task">
                queue a media element task</a> to append the key-value pair |name| →
                |parameterDescriptorSequence| to the <a>node name to parameter descriptor map</a> of the
                associated {{BaseAudioContext}}.
        </div>

        Note: The class constructor should only be looked up once, thus it
        does not have the opportunity to dynamically change after registration.

        <pre class=argumentdef for="AudioWorkletGlobalScope/registerProcessor(name, processorCtor)">
            name: A string key that represents a class constructor to be registered. This key is used to look up the constructor of {{AudioWorkletProcessor}} during construction of an {{AudioWorkletNode}}.
            processorCtor: A class constructor extended from {{AudioWorkletProcessor}}.
        </pre>

        <div>
            <em>Return type:</em> {{undefined}}
        </div>
</dl>

<h5 id="AudioWorkletProcessor-instantiation">
The instantiation of {{AudioWorkletProcessor}}</h5>

At the end of the {{AudioWorkletNode}} construction,
A [=struct=] named
<dfn>processor construction data</dfn>
will be prepared for cross-thread transfer. This
<a spec="infra" lt="struct">struct</a> contains the following
<a spec="infra" for="struct" lt="item">items</a>:

- <dfn for="processor construction data">name</dfn> which is a {{DOMString}}
    that is to be looked up in the
    <a>node name to processor constructor map</a>.
- <dfn for="processor construction data">node</dfn> which is a reference to
    the {{AudioWorkletNode}} created.
- <dfn for="processor construction data">options</dfn> which is a serialized
    {{AudioWorkletNodeOptions}} given to the {{AudioWorkletNode}}'s
    {{AudioWorkletNode()|constructor}}.
- <dfn for="processor construction data">port</dfn> which is a serialized
    {{MessagePort}} paired with the {{AudioWorkletNode}}'s
    {{AudioWorkletNode/port}}.

Upon the arrival of the transferred data on the {{AudioWorkletGlobalScope}},
the <a>rendering thread</a> will invoke the algorithm below:

    <div id="invoking-processor-constructor" algorithm="invoking processor constructor">
        1. Let <var>constructionData</var> be the
            [=processor construction data=] transferred from the
            [=control thread=].

        1. Let <var>processorName</var>, <var>nodeReference</var> and
            <var>serializedPort</var> be
            <var>constructionData</var>'s
            [=processor construction data/name=],
            [=processor construction data/node=], and
            [=processor construction data/port=] respectively.

        1. Let <var>serializedOptions</var> be
            <var>constructionData</var>'s
            [=processor construction data/options=].

        1. Let <var>deserializedPort</var> be the result of
            [$StructuredDeserialize$](<var>serializedPort</var>,
            the current Realm).

        1. Let <var>deserializedOptions</var> be the result of
            [$StructuredDeserialize$](<var>serializedOptions</var>,
            the current Realm).

        1. Let <var>processorCtor</var> be the result of looking
            up  <var>processorName</var> on the
            {{AudioWorkletGlobalScope}}'s
            <a>node name to processor constructor map</a>.

        1. Store <var>nodeReference</var> and
            <var>deserializedPort</var> to
            [=pending processor construction data/node reference=]
            and
            [=pending processor construction data/transferred port=]
            of this {{AudioWorkletGlobalScope}}'s
            [=pending processor construction data=] respectively.

        1. <a spec=webidl lt=construct>Construct a callback function</a> from |processorCtor| with
            the argument of |deserializedOptions|. If any exceptions are thrown in the callback,
            <a>queue a task</a> to the <a>control thread</a> to [=fire an event=] named
            {{AudioWorkletNode/processorerror}} at |nodeReference| using {{ErrorEvent}}.

        1. Empty the [=pending processor construction data=] slot.
    </div>

<h4 interface lt="AudioWorkletNode" id="AudioWorkletNode">
The {{AudioWorkletNode}} Interface</h4>

This interface represents a user-defined {{AudioNode}} which
lives on the <a>control thread</a>. The user can create an
{{AudioWorkletNode}} from a {{BaseAudioContext}}, and such a
node can be connected with other built-in {{AudioNode}}s to form
an audio graph.

<pre class=include>
path: audionode.include
macros:
    noi: 1
    noo: 1
    cc: 2
    cc-mode: max
    cc-interp: speakers
    tail-time: See notes
    tail-time-notes:  Any <a>tail-time</a> is handled by the node itself
</pre>

Every {{AudioWorkletProcessor}} has an associated <dfn>active source</dfn> flag, initially `true`. This flag causes
the node to be retained in memory and perform audio processing in
the absence of any connected inputs.

All tasks posted from an {{AudioWorkletNode}} are posted to the task queue of
its associated {{BaseAudioContext}}.

<xmp class="idl">
[Exposed=Window]
interface AudioParamMap {
    readonly maplike<DOMString, AudioParam>;
};
</xmp>

This interface has "entries", "forEach", "get", "has", "keys",
"values", @@iterator methods and a "size" getter brought by
<code>readonly maplike</code>.

<pre class="idl">
[Exposed=Window, SecureContext]
interface AudioWorkletNode : AudioNode {
    constructor (BaseAudioContext context, DOMString name,
               optional AudioWorkletNodeOptions options = {});
    readonly attribute AudioParamMap parameters;
    readonly attribute MessagePort port;
    attribute EventHandler onprocessorerror;
};
</pre>

<h5 id="AudioWorkletNode-constructors">
Constructors</h5>

<dl dfn-type=constructor dfn-for="AudioWorkletNode">
    : <dfn>AudioWorkletNode(context, name, options)</dfn>
    ::
        <pre class=argumentdef for="AudioWorkletNode/constructor()">
            context: The {{BaseAudioContext}} this new {{AudioWorkletNode}} will be <a href="#associated">associated</a> with.
            name: A string that is a key for the {{BaseAudioContext}}’s <a>node name to parameter descriptor map</a>.
            options: Optional initial parameters value for this {{AudioWorkletNode}}.
        </pre>

        When the constructor is called, the user agent MUST perform the
        following steps on the control thread:

        <div algorithm="AudioWorkletNode()">
            When the {{AudioWorkletNode()|AudioWorkletNode}} constructor
            is invoked with <var>context</var>, <var>nodeName</var>, <var>options</var>:

            1. If <var>nodeName</var> does not exist as a key in the
                {{BaseAudioContext}}’s <a>node name to parameter
                descriptor map</a>, throw a {{InvalidStateError}}
                exception and abort these steps.

            1. Let <var>node</var> be
                <a spec="webidl" lt="this">this</a> value.

            1. <a href="#audionode-constructor-init">Initialize the AudioNode</a>
                <var>node</var> with <var>context</var> and <var>options</var> as
                arguments.

            1. <a href="#configure-with-audioworkletnodeoptions">
                Configure input, output and output channels</a>
                of <var>node</var> with <var>options</var>.
                Abort the remaining steps if any exception is
                thrown.

            1. Let <var>messageChannel</var> be a new {{MessageChannel}}.

            1. Let <var>nodePort</var> be the value of
                <var>messageChannel</var>'s {{MessageChannel/port1}} attribute.

            1. Let <var>processorPortOnThisSide</var> be the value of
                <var>messageChannel</var>'s {{MessageChannel/port2}} attribute.

            1. Let <var>serializedProcessorPort</var> be the result of
                [$StructuredSerializeWithTransfer$](<var>processorPortOnThisSide</var>,
                « <var>processorPortOnThisSide</var> »).

            1. <a href="https://webidl.spec.whatwg.org/#dictionary-to-es">Convert</a>
                <var>options</var> dictionary to <var>optionsObject</var>.

            1. Let <var>serializedOptions</var> be the result of
                [$StructuredSerialize$](<var>optionsObject</var>).

            1. Set <var>node</var>'s {{AudioWorkletNode/port}} to <var>nodePort</var>.

            1. Let <var>parameterDescriptors</var> be the result of retrieval
                of <var>nodeName</var> from <a>node name to parameter descriptor map</a>:

                1. Let <var>audioParamMap</var> be a new {{AudioParamMap}} object.

                1. For each <var>descriptor</var> of
                    <var>parameterDescriptors</var>:

                    1. Let <var>paramName</var> be the value of
                        {{AudioParamDescriptor/name}} member in
                        <var>descriptor</var>.

                    1. Let <var>audioParam</var> be a new
                        {{AudioParam}} instance with
                        {{AudioParamDescriptor/automationRate}},
                        {{AudioParamDescriptor/defaultValue}},
                        {{AudioParamDescriptor/minValue}}, and
                        {{AudioParamDescriptor/maxValue}}
                        having values equal to the values of
                        corresponding members on
                        <var>descriptor</var>.

                    1. Append a key-value pair
                        <var>paramName</var> →
                        <var>audioParam</var> to
                        <var>audioParamMap</var>'s
                        entries.

                1. If {{AudioWorkletNodeOptions/parameterData}} is
                    present on <var>options</var>, perform the
                    following steps:

                    1. Let <var>parameterData</var> be the value of
                        {{AudioWorkletNodeOptions/parameterData}}.

                    1. For each <var>paramName</var> →
                        <var>paramValue</var> of
                        <var>parameterData</var>:

                        1. If there exists a map entry on
                            <var>audioParamMap</var> with
                            key <var>paramName</var>, let
                            <var>audioParamInMap</var> be
                            such entry.

                        1. Set {{AudioParam/value}} property
                            of <var>audioParamInMap</var>
                            to <var>paramValue</var>.

                1. Set <var>node</var>'s {{AudioWorkletNode/parameters}} to <var>audioParamMap</var>.

            1. <a>Queue a control message</a> to
                <a href="#invoking-processor-constructor">invoke</a>
                the {{AudioWorkletProcessor()|constructor}} of
                the corresponding {{AudioWorkletProcessor}} with
                the [=processor construction data=] that consists of:
                <var>nodeName</var>,
                <var>node</var>,
                <var>serializedOptions</var>, and
                <var>serializedProcessorPort</var>.
        </div>
</dl>

<h5 id="AudioWorkletNode-attributes">
Attributes</h5>

<dl dfn-type=attribute dfn-for="AudioWorkletNode">
    : <dfn>onprocessorerror</dfn>
    ::
        When an unhandled exception is thrown from the processor's
        <code>constructor</code>, <code>process</code> method,
        or any user-defined class method, the processor will
        [=queue a media element task=] to [=fire an event=] named <dfn event>processorerror</dfn>
        at the associated {{AudioWorkletNode}} using {{ErrorEvent}}.

        The <code>ErrorEvent</code> is created and initialized
        appropriately with its <code>message</code>,
        <code>filename</code>, <code>lineno</code>, <code>colno</code>
        attributes on the control thread.

        Note that once a unhandled exception is thrown, the processor
        will output silence throughout its lifetime.

    : <dfn>parameters</dfn>
    ::
        The <code>parameters</code> attribute is a collection of
        {{AudioParam}} objects with associated names. This maplike
        object is populated from a list of {{AudioParamDescriptor}}s
        in the {{AudioWorkletProcessor}} class constructor at the
        instantiation.

    : <dfn>port</dfn>
    ::
        Every {{AudioWorkletNode}} has an associated
        <code>port</code> which is the
        {{MessagePort}}. It is connected to the port on the
        corresponding {{AudioWorkletProcessor}} object allowing
        bidirectional communication between the
        {{AudioWorkletNode}} and its {{AudioWorkletProcessor}}.

        Note: Authors that register an event listener on the <code>"message"</code>
        event of this {{AudioWorkletNode/port}} should call {{MessagePort/close}} on
        either end of the {{MessageChannel}} (either in the
        {{AudioWorkletProcessor}} or the {{AudioWorkletNode}} side) to allow for
        resources to be [[html#ports-and-garbage-collection|collected]].
</dl>

<h5 dictionary id="AudioWorkletNodeOptions">
{{AudioWorkletNodeOptions}}</h5>

The {{AudioWorkletNodeOptions}} dictionary can be used
to initialize attibutes in the instance of an {{AudioWorkletNode}}.

<xmp class="idl">
dictionary AudioWorkletNodeOptions : AudioNodeOptions {
    unsigned long numberOfInputs = 1;
    unsigned long numberOfOutputs = 1;
    sequence<unsigned long> outputChannelCount;
    record<DOMString, double> parameterData;
    object processorOptions;
};
</xmp>

<h6 id="dictionary-audioworkletnodeoptions-members">
Dictionary {{AudioWorkletNodeOptions}} Members</h6>

<dl dfn-type=dict-member dfn-for="AudioWorkletNodeOptions">
    : <dfn>numberOfInputs</dfn>
    ::
        This is used to initialize the value of the {{AudioNode}}
        {{AudioNode/numberOfInputs}} attribute.

    : <dfn>numberOfOutputs</dfn>
    ::
        This is used to initialize the value of the {{AudioNode}}
        {{AudioNode/numberOfOutputs}} attribute.

    : <dfn>outputChannelCount</dfn>
    ::
        This array is used to configure the number of channels in
        each output.

    : <dfn>parameterData</dfn>
    ::
        This is a list of user-defined key-value pairs that are used
        to set the initial {{AudioParam/value}} of an {{AudioParam}}
        with the matched name in the {{AudioWorkletNode}}.

    : <dfn>processorOptions</dfn>
    ::
        This holds any user-defined data that may be used to initialize
        custom properties in an {{AudioWorkletProcessor}} instance
        that is associated with the {{AudioWorkletNode}}.
</dl>

<h6 id="configuring-channels-with-audioworkletnodeoptions">
Configuring Channels with {{AudioWorkletNodeOptions}}</h6>

The following algorithm describes how an {{AudioWorkletNodeOptions}} can be
used to configure various channel configurations.

<div id="configure-with-audioworkletnodeoptions" algorithm="configure with AudioWorkletNodeOptions">
    1. Let <var>node</var> be an {{AudioWorkletNode}} instance that is
        given to this algorithm.

    1. If both {{AudioWorkletNodeOptions/numberOfInputs}} and
        {{AudioWorkletNodeOptions/numberOfOutputs}} are zero,
        throw a {{NotSupportedError}} and abort the remaining steps.

    1. If {{AudioWorkletNodeOptions/outputChannelCount}}
         [=map/exists=],

        1. If any value in
            {{AudioWorkletNodeOptions/outputChannelCount}} is zero
            or greater than the implementation’s maximum number
            of channels, throw a {{NotSupportedError}} and abort
            the remaining steps.

        1. If the length of
            {{AudioWorkletNodeOptions/outputChannelCount}} does not
            equal {{AudioWorkletNodeOptions/numberOfOutputs}},
            throw an {{IndexSizeError}} and abort the remaining
            steps.

        1. If both {{AudioWorkletNodeOptions/numberOfInputs}} and
            {{AudioWorkletNodeOptions/numberOfOutputs}} are 1,
            set the channel count of the <var>node</var> output to
            the one value in
            {{AudioWorkletNodeOptions/outputChannelCount}}.

        1. Otherwise set the channel count of the <em>k</em>th output
            of the <var>node</var> to the <em>k</em>th element
            of {{AudioWorkletNodeOptions/outputChannelCount}}
            sequence and return.

    1. If {{AudioWorkletNodeOptions/outputChannelCount}}
         does not [=map/exists=],

        1. If both {{AudioWorkletNodeOptions/numberOfInputs}} and
            {{AudioWorkletNodeOptions/numberOfOutputs}} are 1,
            set the initial channel count of the <var>node</var>
            output to 1 and return.

            NOTE: For this case, the output chanel count will
            change to <a>computedNumberOfChannels</a> dynamically
            based on the input and the
            {{AudioNode/channelCountMode}} at runtime.

        1. Otherwise set the channel count of each output of the
            <var>node</var> to 1 and return.
</div>

<h4 interface lt="AudioWorkletProcessor" id="AudioWorkletProcessor">
The {{AudioWorkletProcessor}} Interface</h4>

This interface represents an audio processing code that runs on the
audio <a>rendering thread</a>. It lives in the {{AudioWorkletGlobalScope}},
and the definition of the class manifests the actual audio processing.
Note that the an {{AudioWorkletProcessor}} construction can only happen as a
result of an {{AudioWorkletNode}} contruction.

<xmp class="idl">
[Exposed=AudioWorklet]
interface AudioWorkletProcessor {
    constructor ();
    readonly attribute MessagePort port;
};

callback AudioWorkletProcessCallback =
  boolean (FrozenArray<FrozenArray<Float32Array>> inputs,
           FrozenArray<FrozenArray<Float32Array>> outputs,
           object parameters);
</xmp>

{{AudioWorkletProcessor}} has two internal slots:

<dl dfn-type=attribute dfn-for="AudioWorkletProcessor">
    : <dfn>[[node reference]]</dfn>
    ::
        A reference to the associated {{AudioWorkletNode}}.

    : <dfn>[[callable process]]</dfn>
    ::
        A boolean flag representing whether [=process()=] is
        a valid function that can be invoked.
</dl>

<h5 id="AudioWorketProcessor-constructors">
Constructors</h5>

<dl dfn-type="constructor" dfn-for="AudioWorkletProcessor">
    : <dfn>AudioWorkletProcessor()</dfn>
    ::
        When the constructor for {{AudioWorkletProcessor}} is invoked,
        the following steps are performed on the <a>rendering thread</a>.

        <div algorithm="AudioWorkletProcessor()">
            1. Let <var>nodeReference</var> be the result of
                looking up
                [=pending processor construction data/node reference=]
                on the
                [=pending processor construction data=] of the
                current {{AudioWorkletGlobalScope}}.
                Throw a {{TypeError}} exception if the slot is
                empty.

            1. Let <var>processor</var> be the
                <a spec="webidl" lt="this">this</a> value.

            1. Set <var>processor</var>'s {{[[node reference]]}} to
                <var>nodeReference</var>.

            1. Set <var>processor</var>'s {{[[callable process]]}}
                to `true`.

            1. Let <var>deserializedPort</var> be the result of
                looking up
                [=pending processor construction data/transferred port=]
                from the
                [=pending processor construction data=].

            1. Set <var>processor</var>’s
                {{AudioWorkletProcessor/port}}
                to <var>deserializedPort</var>.

            1. Empty the [=pending processor construction data=]
                slot.
        </div>
</dl>

<h5 id="AudioWorkletProcessor-attributes">Attributes</h5>

<dl dfn-type=attribute dfn-for="AudioWorkletProcessor">
    : <dfn>port</dfn>
    ::
        Every {{AudioWorkletProcessor}} has an associated
        <code>port</code> which is a {{MessagePort}}. It is connected to
        the port on the corresponding {{AudioWorkletNode}} object
        allowing bidirectional communication between an
        {{AudioWorkletNode}} and its {{AudioWorkletProcessor}}.

        Note: Authors that register an event listener on the <code>"message"</code>
        event of this {{AudioWorkletProcessor/port}} should call
        {{MessagePort/close}} on either end of the {{MessageChannel}} (either in the
        {{AudioWorkletProcessor}} or the {{AudioWorkletNode}} side) to allow for
        resources to be [[html#ports-and-garbage-collection|collected]].
</dl>

<h5 id="callback-audioworketprocess-callback">
Callback {{AudioWorkletProcessCallback}}</h5>

Users can define a custom audio processor by extending
{{AudioWorkletProcessor}}. The subclass MUST define an {{AudioWorkletProcessCallback}}
named <code><dfn>process()</dfn></code> that implements the audio processing
algorithm and may have a static property named
<code><dfn>parameterDescriptors</dfn></code> which is an iterable
of {{AudioParamDescriptor}}s.

The [=process()=] callback function is handled as specified when <a href="#rendering-a-graph">rendering a graph</a>.

<div class="note">
    The return value of this callback controls the lifetime
    of the {{AudioWorkletProcessor}}'s associated
    {{AudioWorkletNode}}.

    This lifetime policy can support a variety of approaches
    found in built-in nodes, including the following:

    * Nodes that transform their inputs, and are active only
        while connected inputs and/or script references exist. Such
        nodes SHOULD return <code>false</code> from
        [=process()=] which allows the presence or absence of
        connected inputs to determine whether the {{AudioWorkletNode}} is
        [=actively processing=].

    * Nodes that transform their inputs, but which remain active
        for a <a>tail-time</a> after their inputs are disconnected. In
        this case, [=process()=] SHOULD return
        `true` for some period of time after
        <code>inputs</code> is found to contain zero channels. The
        current time may be obtained from the global scope's
        {{AudioWorkletGlobalScope/currentTime}} to
        measure the start and end of this tail-time interval, or the
        interval could be calculated dynamically depending on the
        processor's internal state.

    * Nodes that act as sources of output, typically with a
        lifetime. Such nodes SHOULD return `true` from
        [=process()=] until the point at which they are no
        longer producing an output.

    Note that the preceding definition implies that when no
    return value is provided from an implementation of
    [=process()=], the effect is identical to returning
    <code>false</code> (since the effective return value is the falsy
    value {{undefined}}). This is a reasonable behavior for
    any {{AudioWorkletProcessor}} that is active only when it has
    active inputs.
</div>

The example below shows how {{AudioParam}} can be defined and used in an
{{AudioWorkletProcessor}}.

<xmp class="example" highlight="js" title="Subclassing AudioWorkletProcessor">
class MyProcessor extends AudioWorkletProcessor {
  static get parameterDescriptors() {
    return [{
      name: 'myParam',
      defaultValue: 0.5,
      minValue: 0,
      maxValue: 1,
      automationRate: "k-rate"
    }];
  }

  process(inputs, outputs, parameters) {
    // Get the first input and output.
    const input = inputs[0];
    const output = outputs[0];
    const myParam = parameters.myParam;

    // A simple amplifier for single input and output. Note that the
    // automationRate is "k-rate", so it will have a single value at index [0]
    // for each render quantum.
    for (let channel = 0; channel < output.length; ++channel) {
      for (let i = 0; i < output[channel].length; ++i) {
        output[channel][i] = input[channel][i] * myParam[0];
      }
    }
  }
}
</xmp>

<h6 id="audioworkletprocess-callback-parameters" callback lt="AudioWorkletProcessCallback()">
Callback {{AudioWorkletProcessCallback}} Parameters
</h6>
The following describes the parameters to the {{AudioWorkletProcessCallback}} function.

In general, the {{AudioWorkletProcessCallback/inputs!!argument}} and
{{AudioWorkletProcessCallback/outputs!!argument}} arrays will be reused
between calls so that no memory allocation is done.  However, if the
topology changes, because, say, the number of channels in the input or the
output changes, new arrays are reallocated.  New arrays are also
reallocated if any part of the
{{AudioWorkletProcessCallback/inputs!!argument}} or
{{AudioWorkletProcessCallback/outputs!!argument}} arrays are
transferred.

<dl dfn-type=argument dfn-for="AudioWorkletProcessCallback">
    : {{AudioWorkletProcessCallback/inputs!!argument}}, of type <code>{{FrozenArray}}&lt;{{FrozenArray}}&lt;{{Float32Array}}&gt;&gt;</code>
    :: The input audio buffer from the incoming connections provided by the user agent. <code class="nobreak">inputs[n][m]</code> is a {{Float32Array}} of audio samples for the \(m\)th channel of the \(n\)th input. While the number of inputs is fixed at construction, the number of channels can be changed dynamically based on [=computedNumberOfChannels=].

        If there are no [=actively processing=] {{AudioNode}}s connected to the \(n\)th input of the {{AudioWorkletNode}} for the current render quantum, then the content of <code>inputs[n]</code> is an empty array, indicating that zero channels of input are available. This is the only circumstance under which the number of elements of <code>inputs[n]</code> can be zero.

    : {{AudioWorkletProcessCallback/outputs!!argument}}, of type <code>{{FrozenArray}}&lt;{{FrozenArray}}&lt;{{Float32Array}}>></code>
    :: The output audio buffer that is to be consumed by the user agent. <code class="nobreak">outputs[n][m]</code> is a {{Float32Array}} object containing the audio samples for \(m\)th channel of \(n\)th output. Each of the {{Float32Array}}s are zero-filled. The number of channels in the output will match [=computedNumberOfChannels=] only when the node has a single output.

    : {{AudioWorkletProcessCallback/parameters!!argument}}, of type {{object}}
    :: An [=ordered map=] of <var>name</var> → <var>parameterValues</var>. <code>parameters["<var>name</var>"]</code> returns <var>parameterValues</var>, which is a {{FrozenArray}}&lt;{{Float32Array}}> with the automation values of the <var>name</var> {{AudioParam}}.

        For each array, the array contains the [=computedValue=] of the parameter for all frames in the [=render quantum=]. However, if no automation is scheduled during this render quantum, the array MAY have length 1 with the array element being the constant value of the {{AudioParam}} for the [=render quantum=].

        This object is frozen according the the following steps
        <div algorithm="freeze parameter object">
            1. Let |parameter| be the [=ordered map=] of the name and parameter values.
            1. <a href="https://tc39.es/ecma262/#sec-setintegritylevel">SetIntegrityLevel</a>(|parameter|, frozen)
        </div>

        This frozen [=ordered map=] computed in the algorithm is passed to the
        {{AudioWorkletProcessCallback/parameters!!argument}}
        argument.

        Note: This means the object cannot be modified and
        hence the same object can be used for successive calls
        unless length of an array changes.

</dl>

<h5 dictionary id="AudioParamDescriptor">
{{AudioParamDescriptor}}</h5>

The {{AudioParamDescriptor}} dictionary is used to
specify properties for an {{AudioParam}} object
that is used in an {{AudioWorkletNode}}.

<pre class="idl">
dictionary AudioParamDescriptor {
    required DOMString name;
    float defaultValue = 0;
    float minValue = -3.4028235e38;
    float maxValue = 3.4028235e38;
    AutomationRate automationRate = "a-rate";
};
</pre>

<h6 id="dictionary-audioparamdescriptor-members">
Dictionary {{AudioParamDescriptor}} Members</h6>

There are constraints on the values for these members.  See the <a
href="#steps-parameterDescriptorSequence">algorithm for handling an
AudioParamDescriptor</a> for the constraints.

<dl dfn-type=dict-member dfn-for="AudioParamDescriptor">
    : <dfn>automationRate</dfn>
    ::
        Represents the default automation rate.
    : <dfn>defaultValue</dfn>
    ::
        Represents the default value of the parameter.

    : <dfn>maxValue</dfn>
    ::
        Represents the maximum value.

    : <dfn>minValue</dfn>
    ::
        Represents the minimum value.

    : <dfn>name</dfn>
    ::
        Represents the name of the parameter.
</dl>

<h4 id="AudioWorklet-Sequence">
AudioWorklet Sequence of Events</h4>

The following figure illustrates an idealized sequence of events
occurring relative to an {{AudioWorklet}}:

<figure>
    <img alt="" src="images/audioworklet-instantiation-sequence.png" width="784" height="427">
    <figcaption>
        {{AudioWorklet}} sequence
    </figcaption>
</figure>

The steps depicted in the diagram are one possible sequence of
events involving the creation of an {{AudioContext}} and an
associated {{AudioWorkletGlobalScope}}, followed by the creation
of an {{AudioWorkletNode}} and its associated
{{AudioWorkletProcessor}}.

<div algorithm="audioworklet sequence">
    1. An {{AudioContext}} is created.

    2. In the main scope, <code>context.audioWorklet</code> is requested to add a script module.

    2. Since none exists yet, a new {{AudioWorkletGlobalScope}} is created in association with the context. This is the global scope in which {{AudioWorkletProcessor}} class definitions will be evaluated. (On subsequent calls, this previously created scope will be used.)

    2. The imported script is run in the newly created global scope.

    3. As part of running the imported script, an {{AudioWorkletProcessor}} is registered under
        a key (<code>"custom"</code> in the above diagram) within the {{AudioWorkletGlobalScope}}.
        This populates maps both in the global scope and in the {{AudioContext}}.

    3. The promise for the {{addModule()}} call is resolved.

    6. In the main scope, an {{AudioWorkletNode}} is created using
        the user-specified key along with a
        dictionary of options.

    7. As part of the node's creation, this key is used to look up the
        correct {{AudioWorkletProcessor}} subclass for instantiation.

    8. An instance of the {{AudioWorkletProcessor}} subclass is
        instantiated with a structured clone of the same options
        dictionary. This instance is paired with the previously created
        {{AudioWorkletNode}}.
</div>

<h4 id="AudioWorklet-Examples">
AudioWorklet Examples</h4>

<h5 id="the-bitcrusher-node">
The BitCrusher Node</h5>

Bitcrushing is a mechanism by which the quality of an audio
stream is reduced both by quantizing the sample value (simulating
a lower bit-depth), and by quantizing in time resolution
(simulating a lower sample rate). This example shows how to use
{{AudioParam}}s (in this case, treated as
<a>a-rate</a>) inside an
{{AudioWorkletProcessor}}.

<xmp line-numbers class="example" highlight="js" title="BitCrusher - Global Scope">
const context = new AudioContext();
context.audioWorklet.addModule('bitcrusher.js').then(() => {
    const osc = new OscillatorNode(context);
    const amp = new GainNode(context);

    // Create a worklet node. 'BitCrusher' identifies the
    // AudioWorkletProcessor previously registered when
    // bitcrusher.js was imported. The options automatically
    // initialize the correspondingly named AudioParams.
    const bitcrusher = new AudioWorkletNode(context, 'bitcrusher', {
        parameterData: {bitDepth: 8}
    });

    osc.connect(bitcrusher).connect(amp).connect(context.destination);
    osc.start();
});
</xmp>

<xmp line-numbers class="example" highlight="js" title="BitCrusher - AudioWorkletGlobalScope (bitcrusher.js)">
class Bitcrusher extends AudioWorkletProcessor {
    static get parameterDescriptors () {
        return [{
            name: 'bitDepth',
            defaultValue: 12,
            minValue: 1,
            maxValue: 16
        }, {
            name: 'frequencyReduction',
            defaultValue: 0.5,
            minValue: 0,
            maxValue: 1
        }];
    }

    constructor () {
        super();
        this._phase = 0;
        this._lastSampleValue = 0;
    }

    process (inputs, outputs, parameters) {
        const input = inputs[0];
        const output = outputs[0];
        const bitDepth = parameters.bitDepth;
        const frequencyReduction = parameters.frequencyReduction;

        if (bitDepth.length > 1) {
            for (let channel = 0; channel < output.length; ++channel) {
                for (let i = 0; i < output[channel].length; ++i) {
                    let step = Math.pow(0.5, bitDepth[i]);

                    // Use modulo for indexing to handle the case where
                    // the length of the frequencyReduction array is 1.
                    this._phase += frequencyReduction[i % frequencyReduction.length];
                    if (this._phase >= 1.0) {
                        this._phase -= 1.0;
                        this._lastSampleValue =
                            step * Math.floor(input[channel][i] / step + 0.5);
                    }
                    output[channel][i] = this._lastSampleValue;
                }
            }
        } else {
            // Because we know bitDepth is constant for this call,
            // we can lift the computation of step outside the loop,
            // saving many operations.
            const step = Math.pow(0.5, bitDepth[0]);
            for (let channel = 0; channel < output.length; ++channel) {
                for (let i = 0; i < output[channel].length; ++i) {
                    this._phase += frequencyReduction[i % frequencyReduction.length];
                    if (this._phase >= 1.0) {
                        this._phase -= 1.0;
                        this._lastSampleValue =
                            step * Math.floor(input[channel][i] / step + 0.5);
                    }
                    output[channel][i] = this._lastSampleValue;
                }
            }
        }
        // No need to return a value; this node's lifetime is dependent only on its
        // input connections.
    }
};

registerProcessor('bitcrusher', Bitcrusher);
</xmp>

Note: In the definition of {{AudioWorkletProcessor}} class, an
{{InvalidStateError}} will be thrown if the
author-supplied constructor has an explicit return value that is not
<code>this</code> or does not properly call <code>super()</code>.

<h5 id="vu-meter-mode">
VU Meter Node</h5>

This example of a simple sound level meter further illustrates
how to create an {{AudioWorkletNode}} subclass
that acts like a native {{AudioNode}}, accepting
constructor options and encapsulating the inter-thread
communication (asynchronous) between
{{AudioWorkletNode}} and
{{AudioWorkletProcessor}}. This node does not use any output.

<pre line-numbers class="example" highlight="js" title="VUMeterNode - Global Scope (vumeternode.js)">
/* vumeter-node.js: Main global scope */

export default class VUMeterNode extends AudioWorkletNode {
    constructor (context, updateIntervalInMS) {
        super(context, 'vumeter', {
            numberOfInputs: 1,
            numberOfOutputs: 0,
            channelCount: 1,
            processorOptions: {
                updateIntervalInMS: updateIntervalInMS || 16.67
            }
        });

        // States in AudioWorkletNode
        this._updateIntervalInMS = updateIntervalInMS;
        this._volume = 0;

        // Handles updated values from AudioWorkletProcessor
        this.port.onmessage = event => {
            if (event.data.volume)
                this._volume = event.data.volume;
        }
        this.port.start();
    }

    get updateInterval() {
        return this._updateIntervalInMS;
    }

    set updateInterval(updateIntervalInMS) {
        this._updateIntervalInMS = updateIntervalInMS;
        this.port.postMessage({updateIntervalInMS: updateIntervalInMS});
    }

    draw () {
        // Draws the VU meter based on the volume value
        // every |this._updateIntervalInMS| milliseconds.
    }
};
</pre>

<xmp line-numbers class="example" highlight="js" title="VUMeterNode - AudioWorkletGlobalScope (vumeterprocessor.js)">
/* vumeter-processor.js: AudioWorkletGlobalScope */

const SMOOTHING_FACTOR = 0.9;
const MINIMUM_VALUE = 0.00001;

registerProcessor('vumeter', class extends AudioWorkletProcessor {
    constructor (options) {
        super();
        this._volume = 0;
        this._updateIntervalInMS = options.processorOptions.updateIntervalInMS;
        this._nextUpdateFrame = this._updateIntervalInMS;

        this.port.onmessage = event => {
            if (event.data.updateIntervalInMS)
                this._updateIntervalInMS = event.data.updateIntervalInMS;
        }
    }

    get intervalInFrames () {
        return this._updateIntervalInMS / 1000 * sampleRate;
    }

    process (inputs, outputs, parameters) {
        const input = inputs[0];
        // Note that the input will be down-mixed to mono; however, if no inputs are
        // connected then zero channels will be passed in.
        if (input.length > 0) {
            const samples = input[0];
            let sum = 0;
            let rms = 0;

            // Calculated the squared-sum.
            for (let i = 0; i < samples.length; ++i)
                sum += samples[i] * samples[i];

            // Calculate the RMS level and update the volume.
            rms = Math.sqrt(sum / samples.length);
            this._volume = Math.max(rms, this._volume * SMOOTHING_FACTOR);

            // Update and sync the volume property with the main thread.
            this._nextUpdateFrame -= samples.length;
            if (this._nextUpdateFrame < 0) {
                this._nextUpdateFrame += this.intervalInFrames;
                this.port.postMessage({volume: this._volume});
            }
        }

        // Keep on processing if the volume is above a threshold, so that
        // disconnecting inputs does not immediately cause the meter to stop
        // computing its smoothed value.
        return this._volume >= MINIMUM_VALUE;
    }

});
</xmp>

<xmp line-numbers class="example" highlight="js" title="VUMeterNode - Global Scope (main JS file)">
/* index.js: Main global scope, entry point */
import VUMeterNode from './vumeter-node.js';

const context = new AudioContext();
context.audioWorklet.addModule('vumeter-processor.js').then(() => {
    const oscillator = new OscillatorNode(context);
    const vuMeterNode = new VUMeterNode(context, 25);
    oscillator.connect(vuMeterNode);
    oscillator.start();

    function drawMeter () {
        vuMeterNode.draw();
        requestAnimationFrame(drawMeter);
    }

    drawMeter();
});
</xmp>

<h2 id="processing-model">
Processing model</h2>

<h3 id="processing-model-background" class="non-normative">
Background</h3>

<em>This section is non-normative.</em>

Real-time audio systems that require low latency are often
implemented using <em>callback functions</em>, where the operating
system calls the program back when more audio has to be computed in
order for the playback to stay uninterrupted. Such a callback is ideally called
on a high priority thread (often the highest priority on the system).
This means that a program that deals with audio only executes code
from this callback. Crossing thread boundaries or adding some buffering between
a rendering thread and the callback would naturally add latency or make the
system less resilient to glitches.

For this reason, the traditional way of executing asynchronous
operations on the Web Platform, the event loop, does not work here,
as the thread is not <em>continuously executing</em>. Additionally, a
lot of unnecessary and potentially blocking operations are available
from traditional execution contexts (Windows and Workers), which is
not something that is desirable to reach an acceptable level of
performance.

Additionally, the Worker model makes creating a dedicated thread
necessary for a script execution context, while all {{AudioNode}}s
usually share the same execution context.

Note: This section specifies how the end result should look like, not how
it should be implemented. In particular, instead of using message
queue, implementors can use memory that is shared between threads, as
long as the memory operations are not reordered.

<h3 id="control-thread-and-rendering-thread">
Control Thread and Rendering Thread</h3>

The Web Audio API MUST be implemented using a <a>control thread</a>,
and a <a>rendering thread</a>.

The <dfn>control thread</dfn> is the thread from which the
{{AudioContext}} is instantiated, and from which authors
manipulate the audio graph, that is, from where the operations on a
{{BaseAudioContext}} are invoked. The <dfn>rendering thread</dfn>
is the thread on which the actual audio output is computed, in
reaction to the calls from the <a>control thread</a>. It can be a
real-time, callback-based audio thread, if computing audio for an
{{AudioContext}}, or a normal thread if computing audio for an {{OfflineAudioContext}}.

The <a>control thread</a> uses a traditional event loop, as described
in [[HTML]].

The <a>rendering thread</a> uses a specialized rendering loop,
described in the section <a href="#rendering-loop">Rendering an audio
graph</a>

Communication from the <a>control thread</a> to the <a>rendering
thread</a> is done using <a>control message</a> passing.
Communication in the other direction is done using regular event loop
tasks.

Each {{AudioContext}} has a single <dfn>control message
queue</dfn> that is a list of <dfn lt="control message">control
messages</dfn> that are operations running on the <a>rendering
thread</a>.

<dfn id="queuing" lt="queue a control message">Queuing a control message</dfn>
means adding the message to the end of the <a>control message queue</a> of an
{{BaseAudioContext}}.

Note: For example, successfuly calling <code>start()</code> on an
{{AudioBufferSourceNode}} <code>source</code> adds a <a>control
message</a> to the <a href="#control-message-queue">control message
queue</a> of the associated {{BaseAudioContext}}.

<a>Control messages</a> in a <a>control message queue</a> are ordered
by time of insertion. The <dfn>oldest message</dfn> is therefore the
one at the front of the <a>control message queue</a>.

<div algorithm="swapping control message queue">
    <dfn lt="swap">Swapping</dfn> a <a>control message queue</a>
    <var>Q<sub>A</sub></var> with another <a>control message queue</a>
    <var>Q<sub>B</sub></var> means executing the following steps:

    1. Let <var>Q<sub>C</sub></var> be a new, empty <a>control message
        queue</a>.

    2. Move all the <a>control messages</a> <var>Q<sub>A</sub></var> to
        <var>Q<sub>C</sub></var>.

    3. Move all the <a>control messages</a> <var>Q<sub>B</sub></var> to
        <var>Q<sub>A</sub></var>.

    4. Move all the <a>control messages</a> <var>Q<sub>C</sub></var> to
        <var>Q<sub>B</sub></var>.
</div>

<h3 id="asynchronous-operations">
Asynchronous Operations</h3>

Calling methods on {{AudioNode}}s is effectively asynchronous, and
MUST to be done in two phases: a synchronous part and an asynchronous
part. For each method, some part of the execution happens on the
<a>control thread</a> (for example, throwing an exception in case of
invalid parameters), and some part happens on the <a>rendering
thread</a> (for example, changing the value of an {{AudioParam}}).

In the description of each operation on {{AudioNode}}s and
{{BaseAudioContext}}s, the synchronous section is marked with a ⌛. All
the other operations are executed <a href="https://html.spec.whatwg.org/multipage/infrastructure.html#in-parallel">
in parallel</a>, as described in [[HTML]].

The synchronous section is executed on the <a>control thread</a>, and
happens immediately. If it fails, the method execution is aborted,
possibly throwing an exception. If it succeeds, a <a>control
message</a>, encoding the operation to be executed on the
<a>rendering thread</a> is enqueued on the <a>control message
queue</a> of this <a>rendering thread</a>.

The synchronous and asynchronous sections order with respect to other
events MUST be the same: given two operation <var>A</var> and
<var>B</var> with respective synchronous and asynchronous section
<var>A<sub>Sync</sub></var> and <var>A<sub>Async</sub></var>, and
<var>B<sub>Sync</sub></var> and <var>B<sub>Async</sub></var>, if
<var>A</var> happens before <var>B</var>, then
<var>A<sub>Sync</sub></var> happens before
<var>B<sub>Sync</sub></var>, and <var>A<sub>Async</sub></var> happens
before <var>B<sub>Async</sub></var>. In other words, synchronous and
asynchronous sections can't be reordered.

<h3 id="rendering-loop">
Rendering an Audio Graph</h3>

Audio graph rendering is done in blocks of sample-frames, with the size of each
block remaining constant for the lifetime of a {{BaseAudioContext}}. The number of
sample-frames in a block is called <dfn>render quantum size</dfn>, and the block
itself is called a <dfn>render quantum</dfn>. Its default value is 128, and it can
be configured by setting {{AudioContextOptions/renderSizeHint}}.

Operations that happen <dfn>atomically</dfn> on a
given thread can only be executed when no other [=Atomically|atomic=]
operation is running on another thread.

The algorithm for rendering a block of audio from a {{BaseAudioContext}}
<em>G</em> with a <a href="#control-message-queue">control message queue</a>
<em>Q</em> is comprised of multiple steps and explained in further detail
in the algorithm of <a href="#rendering-a-graph">rendering a graph</a>.

The {{AudioContext}} <a>rendering thread</a> is driven by a
<dfn>system-level audio callback</dfn>, that is periodically called
at regular intevals. Each call has a <dfn>system-level audio callback buffer
size</dfn>, which is a varying number of sample-frames that needs to be
computed on time before the next <a>system-level audio callback</a> arrives.

A <dfn>load value</dfn> is computed for each <a>system-level audio
callback</a>, by dividing its execution duration by the <a>system-level
audio callback buffer size</a> divided by {{BaseAudioContext/sampleRate}}.

Ideally the <a>load value</a> is below 1.0, meaning that it took less time
to render the audio that it took to play it out.  An <dfn>audio buffer
underrun</dfn> happens when this <a>load value</a> is greater than 1.0: the
system could not render audio fast enough for real-time.

<div class=note>
    The <a>render quantum size</a> for an audio graph is not necessarily a
    divisor of the <a>system-level audio callback buffer size</a>. This causes
    increased audio latencies and reduced possible maximum load without
    <a>audio buffer underrun</a>.
</div>

Note that the concepts of <a>system-level audio callback</a> and <a>load
value</a> do not apply to {{OfflineAudioContext}}s.

The audio callback is also queued as a task in the <a
href="#control-message-queue">control message queue</a>. The UA MUST perform
the following algorithms to process render quanta to fulfill such task by
filling up the requested buffer size. Along with the <a>control message
queue</a>, each {{AudioContext}} has a regular <a
href="https://html.spec.whatwg.org/multipage/webappapis.html#task-queue">task
queue</a>, called its <dfn for="BaseAudioContext">associated task queue</dfn>
for tasks that are posted to the rendering thread from the control thread. An
additional microtask checkpoint is performed after processing a render quantum
to run any microtasks that might have been queued during the execution of the
`process` methods of {{AudioWorkletProcessor}}.

All tasks posted from an {{AudioWorkletNode}} are posted to the [=associated
task queue=] of its associated {{BaseAudioContext}}.

<div id="rendering-initialization" algorithm="initialize rendering loop">
    The following step MUST be performed once before the rendering loop starts.

    1. Set the internal slot <dfn attribute
        for="BaseAudioContext">[[current frame]]</dfn> of the
        {{BaseAudioContext}} to 0. Also set {{BaseAudioContext/currentTime}} to 0.
</div>

<div id="rendering-a-graph" algorithm="rendering a graph">
  The following steps MUST be performed when rendering a render quantum.

    1. Let <var>render result</var> be <code>false</code>.

    2. Process the [=control message queue=].

        1. Let <var>Q<sub>rendering</sub></var> be an empty [=control message
            queue=]. [=Atomically=] [=swap=] <var>Q<sub>rendering</sub></var>
            with the current [=control message queue=].

        2. While there are messages in <var>Q<sub>rendering</sub></var>, execute the
            following steps:

            1. Execute the asynchronous section of the [=oldest message=] of
                <var>Q<sub>rendering</sub></var>.

            2. Remove the [=oldest message=] of <var>Q<sub>rendering</sub></var>.


    3. Process the {{BaseAudioContext}}'s [=associated task queue=].


        1. Let <var>task queue</var> be the {{BaseAudioContext}}'s [=associated task queue=].
        2. Let <var>task count</var> be the number of tasks in the in <var>task queue</var>
        3. While <var>task count</var> is not equal to 0, execute the following steps:
            1. Let <var>oldest task</var> be the first runnable task in <var>task queue</var>, and remove it from <var>task queue</var>.
            2. Set the rendering loop's currently running task to <var>oldest task</var>.
            3. Perform <var>oldest task</var>'s steps.
            4. Set the rendering loop currently running task back to <code>null</code>.
            6. Decrement <var>task count</var>
            5. Perform a microtask checkpoint.

    4. Process a render quantum.

        1. If the {{[[rendering thread state]]}} of the {{BaseAudioContext}} is not
            <code>running</code>, return false.

        2. Order the {{AudioNode}}s of the {{BaseAudioContext}} to be processed.

            1. Let <var>ordered node list</var> be an empty list of {{AudioNode}}s and
                {{AudioListener}}. It will contain an ordered list of {{AudioNode}}s and
                the {{AudioListener}} when this ordering algorithm terminates.

            2. Let <var>nodes</var> be the set of all nodes created by this
                {{BaseAudioContext}}, and still alive.

            3. Add the {{AudioListener}} to <var>nodes</var>.

            4. Let <var>cycle breakers</var> be an empty set of {{DelayNode}}s. It will
                contain all the {{DelayNode}}s that are part of a cycle.

            5. For each {{AudioNode}} <var>node</var> in <var>nodes</var>:

                1. If <var>node</var> is a {{DelayNode}} that is part of a cycle, add it
                    to <var>cycle breakers</var> and remove it from <var>nodes</var>.

            6. For each {{DelayNode}} <var>delay</var> in <var>cycle breakers</var>:

                1. Let <var>delayWriter</var> and <var>delayReader</var> respectively be a
                        <a>DelayWriter</a> and a <a>DelayReader</a>, for <var>delay</var>.
                        Add <var>delayWriter</var> and <var>delayReader</var> to
                        <var>nodes</var>. Disconnect <var>delay</var> from all its input and
                        outputs.

                        Note: This breaks the cycle: if a <code>DelayNode</code> is in a
                        cycle, its two ends can be considered separately, because delay lines
                        cannot be smaller than one render quantum when in a cycle.

            7. If <var>nodes</var> contains cycles, [=mute=] all the
                {{AudioNode}}s that are part of this cycle, and remove them from
                <var>nodes</var>.

            8. Consider all elements in <var>nodes</var> to be unmarked. While there are unmarked elements in <var>nodes</var>:

                1. Choose an element <var>node</var> in <var>nodes</var>.

                2. [=Visit=] <var>node</var>.

                <div algorithm="visiting a node">
                    <dfn lt="Visit">Visiting a node</dfn> means performing
                    the following steps:

                    1. If <var>node</var> is marked, abort these steps.

                    2. Mark <var>node</var>.

                    3. If <var>node</var> is an {{AudioNode}}, [=Visit=] each
                        {{AudioNode}} connected to the input of <var>node</var>.

                    4. For each {{AudioParam}} <var>param</var> of <var>node</var>:
                        1. For each {{AudioNode}} <var>param input node</var> connected to <var>param</var>:
                            1. [=Visit=] <var>param input node</var>

                    5. Add <var>node</var> to the beginning of <var ignore>ordered node list</var>.
                </div>

            9. Reverse the order of <var>ordered node list</var>.

        4. [[#computation-of-value|Compute the value(s)]] of the
            {{AudioListener}}'s {{AudioParam}}s for this block.

        5. For each {{AudioNode}}, in <var>ordered node list</var>:

            1. For each {{AudioParam}} of this {{AudioNode}}, execute these steps:

                1. If this {{AudioParam}} has any {{AudioNode}} connected to it,
                    [[#channel-up-mixing-and-down-mixing|sum]] the buffers
                    [=Making a buffer available for reading|made available for reading=] by
                    all {{AudioNode}} connected to this {{AudioParam}},
                    [[#down-mix|down mix]] the resulting buffer down to a mono
                    channel, and call this buffer the <dfn id="input-audioparam-buffer">
                    input AudioParam buffer</dfn>.

                2. [[#computation-of-value|Compute the value(s)]] of this
                    {{AudioParam}} for this block.

                3. [=Queue a control message=] to set the {{[[current value]]}} slot
                    of this {{AudioParam}} according to [[#computation-of-value]].

            2. If this {{AudioNode}} has any {{AudioNode}}s connected to its input,
                [[#channel-up-mixing-and-down-mixing|sum]] the buffers
                [=Making a buffer available for reading|made available for reading=] by all
                {{AudioNode}}s connected to this {{AudioNode}}. The resulting buffer is
                called the <dfn>input buffer</dfn>.
                [[#channel-up-mixing-and-down-mixing|Up or down-mix]] it to
                match if number of input channels of this {{AudioNode}}.

            3. If this {{AudioNode}} is a <a>source node</a>,
                [=Computing a block of audio|compute a block of audio=], and
                [=Making a buffer available for reading|make it available for reading=].

            4. If this {{AudioNode}} is an {{AudioWorkletNode}}, execute these substeps:

                1. Let |processor| be the associated {{AudioWorkletProcessor}}
                    instance of {{AudioWorkletNode}}.

                1. Let |O| be the ECMAScript object corresponding to |processor|.

                1. Let |processCallback| be an uninitialized variable.

                1. Let |completion| be an uninitialized variable.

                1. [=Prepare to run script=] with the [=current settings object=].

                1. [=Prepare to run a callback=] with the [=current settings object=].

                1. Let |getResult| be
                    <a href="https://tc39.github.io/ecma262/#sec-get-o-p">
                    Get</a>(|O|, "process").

                1. If |getResult| is an
                    <a href="https://tc39.github.io/ecma262/#sec-completion-record-specification-type">
                    abrupt completion</a>, set |completion| to |getResult| and jump to the step
                    labeled <a href="#audio-worklet-render-return">return</a>.

                1. Set |processCallback| to |getResult|.\[[Value]].

                1. If <a href="https://tc39.es/ecma262/#sec-returnifabrupt-shorthands">!</a>
                    <a href="https://tc39.es/ecma262/#sec-iscallable">
                    IsCallable</a>(|processCallback|) is `false`, then:

                    1. Set |completion| to new
                        <a href="https://tc39.es/ecma262/#sec-throwcompletion">Completion</a>
                        {\[[Type]]: throw, \[[Value]]: a newly created
                        <a href="https://tc39.es/ecma262/#sec-native-error-types-used-in-this-standard-typeerror">
                        TypeError</a> object, \[[Target]]: empty}.

                    1. Jump to the step labeled
                        <a href="#audio-worklet-render-return">return</a>.

                1. Set {{[[callable process]]}} to `true`.

                1. Perform the following substeps:

                    1. Let |args| be a
                        <a href="https://webidl.spec.whatwg.org/#web-idl-arguments-list">
                        Web IDL arguments list</a> consisting of
                        {{AudioWorkletProcessCallback/inputs}},
                        {{AudioWorkletProcessCallback/outputs}}, and
                        {{AudioWorkletProcessCallback/parameters}}.

                    1. Let |esArgs| be the result of
                        <a href="https://webidl.spec.whatwg.org/#web-idl-arguments-list-converting">
                        converting</a> |args| to an ECMAScript arguments list.

                    1. Let |callResult| be the <a href="https://tc39.github.io/ecma262/#sec-call">
                        Call</a>(|processCallback|, |O|, |esArgs|). This operation
                        [=Computing a block of audio|computes a block of audio=] with |esArgs|.
                        Upon a successful function call, a buffer containing copies of
                        the elements of the {{Float32Array}}s passed via the
                        {{AudioWorkletProcessCallback/outputs}} is
                        [=Making a buffer available for reading|made available for reading=].
                        Any {{Promise}} resolved within this call will be queued into the
                        microtask queue in the {{AudioWorkletGlobalScope}}.

                    1. If |callResult| is an
                        <a href="https://tc39.github.io/ecma262/#sec-completion-record-specification-type">
                        abrupt completion</a>, set |completion| to |callResult| and jump to the
                        step labeled <a href="#audio-worklet-render-return">return</a>.

                    1. Set |processor|’s <a>active source</a> flag to
                        <a href="https://tc39.github.io/ecma262/#sec-toboolean">
                        ToBoolean</a>(|callResult|.\[[Value]]).

                1. <b id="audio-worklet-render-return">Return:</b> at this point |completion|
                    will be set to an ECMAScript
                    <a href="https://tc39.es/ecma262/#sec-completion-record-specification-type">completion</a> value.

                    1. [=Clean up after running a callback=] with the [=current settings object=].

                    1. [=Clean up after running script=] with the [=current settings object=].

                    1. If |completion| is an
                        <a href="https://tc39.github.io/ecma262/#sec-completion-record-specification-type">
                        abrupt completion</a>:

                        1. Set {{[[callable process]]}} to `false`.

                        1. Set |processor|'s <a>active source</a> flag to `false`.

                        1. [=Making a buffer available for reading|Make a silent output buffer available for reading=].

                        1. <a>Queue a task</a> to the <a>control thread</a> to [=fire an event=]
                            named {{AudioWorkletNode/processorerror}} at the associated
                            {{AudioWorkletNode}} using {{ErrorEvent}}.

            5. If this {{AudioNode}} is a <a>destination node</a>,
                [=Recording the input|record the input=] of this {{AudioNode}}.

            6. Else, [=processing an input buffer|process=] the <a>input buffer</a>, and
                [=Making a buffer available for reading|make available for reading=] the
                resulting buffer.

        6. [=Atomically=] perform the following steps:

            1. Increment {{[[current frame]]}} by the [=render quantum size=].

            2. Set {{BaseAudioContext/currentTime}} to {{[[current frame]]}} divided
                by {{BaseAudioContext/sampleRate}}.

        7. Set <var>render result</var> to <code>true</code>.

    5. [=Perform a microtask checkpoint=].

    6. Return <var>render result</var>.
</div>

<dfn id="mute">Muting</dfn> an {{AudioNode}} means that its
output MUST be silence for the rendering of this audio block.

<dfn id="available-for-reading">Making a buffer available for reading</dfn>
from an {{AudioNode}} means putting it in a state where other
{{AudioNode}}s connected to this {{AudioNode}} can safely
read from it.

Note: For example, implementations can choose to allocate a new buffer,
or have a more elaborate mechanism, reusing an existing buffer
that is now unused.

<dfn>Recording the input</dfn> of an {{AudioNode}}
means copying the input data of this {{AudioNode}} for future
usage.

<dfn>Computing a block of audio</dfn> means
running the algorithm for this {{AudioNode}} to produce
{{BaseAudioContext/[[render quantum size]]}} sample-frames.

<dfn>Processing an input buffer</dfn> means
running the algorithm for an {{AudioNode}}, using an <a>input
buffer</a> and the value(s) of the {{AudioParam}}(s) of this
{{AudioNode}} as the input for this algorithm.

<h3 id="interruption-handling">Handling an interruption on the {{AudioContext}}</h3>

An <dfn>interruption</dfn> is an event generated by the user agent when it needs
to halt audio playback for an {{AudioContext}}. For example, The user agent may
create an interruption when another application requests exclusive access to the
audio output hardware.

When an [=interruption=] happens, the user agent MUST <a>queue a control message</a>
to interrupt the {{AudioContext}}.

Running a <a>control message</a> to <dfn attribute for="AudioContext"
lt="interruption-start">interrupt an {{AudioContext}}</dfn> |context|
means running these steps on the <a>rendering thread</a>:

1. If the |context|'s {{[[rendering thread state]]}} is 
    {{AudioContextState/closed}} or {{AudioContextState/interrupted}}, abort
    these steps.

1. If the |context|'s {{[[rendering thread state]]}} is
    {{AudioContextState/running}}:

    1. Attempt to <a>release system resources</a>.

    1. [=Queue a media element task=] to execute the following steps:

        1. Set the |context|'s {{[[control thread state]]}} to
            {{AudioContextState/interrupted}}.

        1. Set the |context|'s {{[[state before interruption]]}} slot to
            "{{AudioContextState/running}}".

        1. [=Fire an event=] named {{BaseAudioContext/statechange}} at the
            |context|.

1. If the |context|'s {{[[rendering thread state]]}} is
    {{AudioContextState/suspended}}:

    1. [=Queue a media element task=] to execute the following steps:

        1. Set the |context|'s {{[[control thread state]]}} to
            {{AudioContextState/interrupted}}.
        
        1. Set the |context|'s {{[[state before interruption]]}} slot to
            "{{AudioContextState/suspended}}".

1. Set the |context|'s {{[[rendering thread state]]}} to
    {{AudioContextState/interrupted}}.

Note: If the {{AudioContext}} is {{AudioContextState/suspended}} a
{{BaseAudioContext/statechange}} event is not fired for privacy reasons to avoid
over-sharing user activity - e.g. when a phone call comes in or when the screen
gets locked.

When an [=interruption=] ends, the user agent MUST <a>queue a control message</a>
to <dfn attribute for="AudioContext" lt="interruption-end">end the
{{AudioContext}} interruption</dfn>.

Running a <a>control message</a> to end an {{AudioContext}} |context|
[=interruption=] means running these steps on the <a>rendering thread</a>:

1. If the |context|'s {{[[rendering thread state]]}} is not
    {{AudioContextState/interrupted}}, abort these steps.

1. If the |context|'s {{[[state before interruption]]}} is
    "{{AudioContextState/running}}":

    1. Attempt to <a href="#acquiring">acquire system resources</a>.

    1. Set the {{[[rendering thread state]]}} on the {{AudioContext}} to
        "{{AudioContextState/running}}".

    1. Start <a href="#rendering-loop">rendering the audio graph</a>.

    1. [=Queue a media element task=] to execute the following steps:

        1. If the {{BaseAudioContext/state}} attribute of the {{AudioContext}}
            is not already "{{AudioContextState/running}}":

            1. Set the |context|'s {{[[control thread state]]}} to
                "{{AudioContextState/running}}".

            1. [=Fire an event=] named {{BaseAudioContext/statechange}} at the
                |context|.

1. If the |context|'s {{[[state before interruption]]}} is
    "{{AudioContextState/suspended}}"

    1. Set the {{[[rendering thread state]]}} on the {{AudioContext}} to
        <code>suspended</code>.

    1. [=Queue a media element task=] to execute the following steps:

        1. Set the |context|'s {{[[control thread state]]}} to
            <code>suspended</code>.

1. Set the |context|'s {{[[state before interruption]]}} to `null`.

<h3 id="error-handling-on-a-running-audio-context">
    Handling an error from System Audio Resources on the {{AudioContext}}</h3>

The {{AudioContext}} |audioContext| performs the following steps on <a>rendering thread</a> in the
    event of an audio system resource error.

1. If the |audioContext|'s {{[[rendering thread state]]}} is <code>running</code>
    or <code>interrupted</code>:

    1. Attempt to <a>release system resources</a>.

    1. Set the |audioContext|'s {{[[rendering thread state]]}} to <code>suspended</code>.

    1. [=Queue a media element task=] to execute the following steps:

        1. [=Fire an event=] named {{AudioContext/error}} at |audioContext|.

        1. Set the |audioContext|'s {{[[suspended by user]]}} to <code>false</code>.

        1. Set the |audioContext|'s {{[[control thread state]]}} to <code>suspended</code>.

        1. Set the |audioContext|'s {{BaseAudioContext/state}} attribute to 
            "{{AudioContextState/suspended}}".

        1. [=Fire an event=] named {{BaseAudioContext/statechange}} at the |audioContext|.

    1. Abort these steps.

1. If the |audioContext|'s {{[[rendering thread state]]}} is <code>suspended</code>:

    1. [=Queue a media element task=]to execute the following steps:

        1. [=Fire an event=] named {{AudioContext/error}} at |audioContext|.

Note: An example of system audio resource errors would be when an external or wireless audio device
    becoming disconnected during the active rendering of the {{AudioContext}}.

<h3 id="unloading-a-document">Unloading a document</h3>
    Additional <a href=
    "https://html.spec.whatwg.org/#unloading-document-cleanup-steps">unloading
    document cleanup steps</a> are defined for documents that use
    {{BaseAudioContext}}:

1. Reject all the promises of {{BaseAudioContext/[[pending promises]]}} with
    <code>InvalidStateError</code>, for each {{AudioContext}} and
    {{OfflineAudioContext}} whose relevant global object is the same as
    the document's associated Window.
2. Stop all {{decoding thread}}s.
3. <a>Queue a control message</a> to {{AudioContext/close()}} the
    {{AudioContext}} or {{OfflineAudioContext}}.

<h2 id="DynamicLifetime">
Dynamic Lifetime</h2>

<h3 id="dynamic-lifetime-background" class="informative">
Background</h3>

Note: The normative description of {{AudioContext}} and {{AudioNode}} lifetime characteristics is
    described by the <a href="#lifetime-AudioContext">AudioContext lifetime</a> and <a
    href="#AudioNode-actively-processing">AudioNode lifetime</a>.

<em>This section is non-normative.</em>

In addition to allowing the creation of static routing
configurations, it should also be possible to do custom effect
routing on dynamically allocated voices which have a limited
lifetime. For the purposes of this discussion, let's call these
short-lived voices "notes". Many audio applications incorporate the
ideas of notes, examples being drum machines, sequencers, and 3D
games with many one-shot sounds being triggered according to game
play.

In a traditional software synthesizer, notes are dynamically
allocated and released from a pool of available resources. The note
is allocated when a MIDI note-on message is received. It is released
when the note has finished playing either due to it having reached
the end of its sample-data (if non-looping), it having reached a
sustain phase of its envelope which is zero, or due to a MIDI
note-off message putting it into the release phase of its envelope.
In the MIDI note-off case, the note is not released immediately, but
only when the release envelope phase has finished. At any given time,
there can be a large number of notes playing but the set of notes is
constantly changing as new notes are added into the routing graph,
and old ones are released.

The audio system automatically deals with tearing-down the part of
the routing graph for individual "note" events. A "note" is
represented by an {{AudioBufferSourceNode}}, which
can be directly connected to other processing nodes. When the note
has finished playing, the context will automatically release the
reference to the {{AudioBufferSourceNode}}, which in
turn will release references to any nodes it is connected to, and so
on. The nodes will automatically get disconnected from the graph and
will be deleted when they have no more references. Nodes in the graph
which are long-lived and shared between dynamic voices can be managed
explicitly. Although it sounds complicated, this all happens
automatically with no extra handling required.

<h3 id="dynamic-lifetime-example">
Example</h3>

<figure>
    <img alt="dynamic allocation" src="images/dynamic-allocation.png"
    width="671" height="221">
    <figcaption>
        A graph featuring a subgraph that will be released early.
    </figcaption>
</figure>

The low-pass filter, panner, and second gain nodes are directly
connected from the one-shot sound. So when it has finished playing
the context will automatically release them (everything within the
dotted line). If there are no longer any references to the one-shot
sound and connected nodes, then they will be immediately removed from
the graph and deleted. The streaming source has a global reference
and will remain connected until it is explicitly disconnected. Here's
how it might look in JavaScript:

<pre line-numbers class="example" highlight="js">
let context = 0;
let compressor = 0;
let gainNode1 = 0;
let streamingAudioSource = 0;

// Initial setup of the "long-lived" part of the routing graph
function setupAudioContext() {
        context = new AudioContext();

        compressor = context.createDynamicsCompressor();
        gainNode1 = context.createGain();

        // Create a streaming audio source.
        const audioElement = document.getElementById('audioTagID');
        streamingAudioSource = context.createMediaElementSource(audioElement);
        streamingAudioSource.connect(gainNode1);

        gainNode1.connect(compressor);
        compressor.connect(context.destination);
}

// Later in response to some user action (typically mouse or key event)
// a one-shot sound can be played.
function playSound() {
        const oneShotSound = context.createBufferSource();
        oneShotSound.buffer = dogBarkingBuffer;

        // Create a filter, panner, and gain node.
        const lowpass = context.createBiquadFilter();
        const panner = context.createPanner();
        const gainNode2 = context.createGain();

        // Make connections
        oneShotSound.connect(lowpass);
        lowpass.connect(panner);
        panner.connect(gainNode2);
        gainNode2.connect(compressor);

        // Play 0.75 seconds from now (to play immediately pass in 0)
        oneShotSound.start(context.currentTime + 0.75);
}
</pre>

<h2 id="channel-up-mixing-and-down-mixing">
Channel Up-Mixing and Down-Mixing</h2>

<em>This section is normative.</em>

An AudioNode input has <dfn dfn>mixing rules</dfn> for combining the channels from all
of the connections to it. As a simple example, if an input is connected
from a mono output and a stereo output, then the mono connection will
usually be up-mixed to stereo and summed with the stereo connection.
But, of course, it's important to define the exact <a>mixing
rules</a> for every input to every {{AudioNode}}. The
default mixing rules for all of the inputs have been chosen so that
things "just work" without worrying too much about the details,
especially in the very common case of mono and stereo streams. Of
course, the rules can be changed for advanced use cases, especially
multi-channel.

To define some terms, <dfn dfn>up-mixing</dfn> refers to the process of
taking a stream with a smaller number of channels and converting it to
a stream with a larger number of channels. <dfn dfn>down-mixing</dfn> refers
to the process of taking a stream with a larger number of channels and
converting it to a stream with a smaller number of channels.

An {{AudioNode}} input needs to mix all the outputs
connected to this input. As part of this process it computes an
internal value <a>computedNumberOfChannels</a> representing the actual
number of channels of the input at any given time.

<div algorithm="channel mixing">
    For each input of an {{AudioNode}}, an implementation
    MUST:

    1. Compute <a>computedNumberOfChannels</a>.

    2. For each connection to the input:

        1. [=up-mix=] or [=down-mix=] the connection to
            <a>computedNumberOfChannels</a> according to the
            {{ChannelInterpretation}}
            value given by the node's {{AudioNode/channelInterpretation}} attribute.

        2. Mix it together with all of the other mixed streams (from other
            connections). This is a straight-forward summing together of each of
            the corresponding channels that have been
            [=up-mix|up-mixed=] or [=down-mix|down-mixed=]
            in step 1 for each connection.  </div>

<h3 id="ChannelLayouts">
Speaker Channel Layouts</h3>

When {{AudioNode/channelInterpretation}} is
"{{ChannelInterpretation/speakers}}" then the
[=up-mix|up-mixing=] and [=down-mix|down-mixing=] is defined for specific channel layouts.

Mono (one channel), stereo (two channels), quad (four channels), and
5.1 (six channels) MUST be supported. Other channel layouts may be
supported in future version of this specification.

<h3 id="ChannelOrdering">
Channel Ordering</h3>

Channel ordering is defined by the following table. Individual
multichannel formats MAY not support all intermediate channels.
Implementations MUST present the channels provided in the order
defined below, skipping over those channels not present.

<table class="channels">
    <thead>
        <tr>
            <th scope="col">Order
            <th scope="col">Label
            <th scope="col">Mono
            <th scope="col">Stereo
            <th scope="col">Quad
            <th scope="col">5.1
    <tbody>
        <tr><td>0 <td>SPEAKER_FRONT_LEFT <td>0 <td>0 <td>0 <td>0
        <tr><td>1 <td>SPEAKER_FRONT_RIGHT <td> <td>1 <td>1 <td>1
        <tr><td>2 <td>SPEAKER_FRONT_CENTER <td> <td> <td> <td>2
        <tr><td>3 <td>SPEAKER_LOW_FREQUENCY <td> <td> <td> <td>3
        <tr><td>4 <td>SPEAKER_BACK_LEFT <td> <td> <td>2 <td>4
        <tr><td>5 <td>SPEAKER_BACK_RIGHT <td> <td> <td>3 <td>5
        <tr><td>6 <td>SPEAKER_FRONT_LEFT_OF_CENTER <td> <td> <td> <td>
        <tr><td>7 <td>SPEAKER_FRONT_RIGHT_OF_CENTER <td> <td> <td> <td>
        <tr><td>8 <td>SPEAKER_BACK_CENTER <td> <td> <td> <td>
        <tr><td>9 <td>SPEAKER_SIDE_LEFT <td> <td> <td> <td>
        <tr><td>10 <td>SPEAKER_SIDE_RIGHT <td> <td> <td> <td>
        <tr><td>11 <td>SPEAKER_TOP_CENTER <td> <td> <td> <td>
        <tr><td>12 <td>SPEAKER_TOP_FRONT_LEFT <td> <td> <td> <td>
        <tr><td>13 <td>SPEAKER_TOP_FRONT_CENTER <td> <td> <td> <td>
        <tr><td>14 <td>SPEAKER_TOP_FRONT_RIGHT <td> <td> <td> <td>
        <tr><td>15 <td>SPEAKER_TOP_BACK_LEFT <td> <td> <td> <td>
        <tr><td>16 <td>SPEAKER_TOP_BACK_CENTER <td> <td> <td> <td>
        <tr><td>17 <td>SPEAKER_TOP_BACK_RIGHT <td> <td> <td> <td>
</table>

<h3 id="channels-tail-time">
Implication of tail-time on input and output channel count</h3>

When an {{AudioNode}} has a non-zero <a>tail-time</a>, and an output channel
count that depends on the input channels count, the {{AudioNode}}'s
<a>tail-time</a> must be taken into account when the input channel count
changes.

When there is a decrease in input channel count, the change in output channel
count MUST happen when the input that was received with greater channel count no
longer affects the output.

When there is an increase in input channel count, the behavior depends on the
{{AudioNode}} type:

- For a {{DelayNode}} or a {{DynamicsCompressorNode}}, the number of output
    channels MUST increase when the input that was received with greater channel
    count begins to affect the output.

- For other {{AudioNode}}s that have a <a>tail-time</a>, the number of output
    channels MUST increase immediately.

    Note: For a {{ConvolverNode}}, this only applies to the case where the impulse
    response is mono. Otherwise, the {{ConvolverNode}} always outputs a stereo
    signal regardless of its input channel count.

Note: Intuitively, this allows not losing stereo information as part of
processing: when multiple input render quanta of different channel count
contribute to an output render quantum then the output render quantum's channel
count is a superset of the input channel count of the input render quantums.

<h3 id="UpMix-sub">
Up Mixing Speaker Layouts</h3>

<pre>
Mono up-mix:

    1 -&gt; 2 : up-mix from mono to stereo
        output.L = input;
        output.R = input;

    1 -&gt; 4 : up-mix from mono to quad
        output.L = input;
        output.R = input;
        output.SL = 0;
        output.SR = 0;

    1 -&gt; 5.1 : up-mix from mono to 5.1
        output.L = 0;
        output.R = 0;
        output.C = input; // put in center channel
        output.LFE = 0;
        output.SL = 0;
        output.SR = 0;

Stereo up-mix:

    2 -&gt; 4 : up-mix from stereo to quad
        output.L = input.L;
        output.R = input.R;
        output.SL = 0;
        output.SR = 0;

    2 -&gt; 5.1 : up-mix from stereo to 5.1
        output.L = input.L;
        output.R = input.R;
        output.C = 0;
        output.LFE = 0;
        output.SL = 0;
        output.SR = 0;

Quad up-mix:

    4 -&gt; 5.1 : up-mix from quad to 5.1
        output.L = input.L;
        output.R = input.R;
        output.C = 0;
        output.LFE = 0;
        output.SL = input.SL;
        output.SR = input.SR;
</pre>

<h3 id="down-mix">
Down Mixing Speaker Layouts</h3>

A down-mix will be necessary, for example, if processing 5.1 source
material, but playing back stereo.

<pre>
Mono down-mix:

    2 -&gt; 1 : stereo to mono
        output = 0.5 * (input.L + input.R);

    4 -&gt; 1 : quad to mono
        output = 0.25 * (input.L + input.R + input.SL + input.SR);

    5.1 -&gt; 1 : 5.1 to mono
        output = sqrt(0.5) * (input.L + input.R) + input.C + 0.5 * (input.SL + input.SR)

Stereo down-mix:

    4 -&gt; 2 : quad to stereo
        output.L = 0.5 * (input.L + input.SL);
        output.R = 0.5 * (input.R + input.SR);

    5.1 -&gt; 2 : 5.1 to stereo
        output.L = L + sqrt(0.5) * (input.C + input.SL)
        output.R = R + sqrt(0.5) * (input.C + input.SR)

Quad down-mix:

    5.1 -&gt; 4 : 5.1 to quad
        output.L = L + sqrt(0.5) * input.C
        output.R = R + sqrt(0.5) * input.C
        output.SL = input.SL
        output.SR = input.SR
</pre>

<h3 id="ChannelRules-section">
Channel Rules Examples</h3>

<pre line-numbers class="example" highlight="js">
    // Set gain node to explicit 2-channels (stereo).
    gain.channelCount = 2;
    gain.channelCountMode = "explicit";
    gain.channelInterpretation = "speakers";

    // Set "hardware output" to 4-channels for DJ-app with two stereo output busses.
    context.destination.channelCount = 4;
    context.destination.channelCountMode = "explicit";
    context.destination.channelInterpretation = "discrete";

    // Set "hardware output" to 8-channels for custom multi-channel speaker array
    // with custom matrix mixing.
    context.destination.channelCount = 8;
    context.destination.channelCountMode = "explicit";
    context.destination.channelInterpretation = "discrete";

    // Set "hardware output" to 5.1 to play an HTMLAudioElement.
    context.destination.channelCount = 6;
    context.destination.channelCountMode = "explicit";
    context.destination.channelInterpretation = "speakers";

    // Explicitly down-mix to mono.
    gain.channelCount = 1;
    gain.channelCountMode = "explicit";
    gain.channelInterpretation = "speakers";
</pre>

<h2 id="audio-signal-values">
Audio Signal Values</h2>

<h3 id="audio-sample-format">
Audio sample format</h3>

<dfn lt="linear PCM">Linear pulse code modulation</dfn> (linear PCM) describes a
format where the audio values are sampled at a regular interval, and where the
quantization levels between two successive values are linearly uniform.

Whenever signal values are exposed to script in this specification, they are in
linear 32-bit floating point pulse code modulation format (linear 32-bit float
PCM), often in the form of {{Float32Array}} objects.

<h3 id="audio-values-rendering">
Rendering</h3>

The range of all audio signals at a destination node of any audio graph
is nominally [-1, 1]. The audio rendition of signal values outside this
range, or of the values <code>NaN</code>, positive infinity or negative
infinity, is undefined by this specification.


<h2 id="Spatialization">
Spatialization/Panning</h2>

<h3 id="Spatialization-background">
Background</h3>

A common feature requirement for modern 3D games is the ability to
dynamically spatialize and move multiple audio sources in 3D space.
For example <a href="https://openal.org">OpenAL</a> has this ability.

Using a {{PannerNode}}, an audio stream can be
spatialized or positioned in space relative to an
{{AudioListener}}. A
{{BaseAudioContext}} will contain a single
{{AudioListener}}. Both panners and listeners have a
position in 3D space using a right-handed cartesian coordinate
system. The units used in the coordinate system are not defined, and
do not need to be because the effects calculated with these
coordinates are independent/invariant of any particular units such as
meters or feet. {{PannerNode}} objects (representing
the source stream) have an <em>orientation</em> vector representing
in which direction the sound is projecting. Additionally, they have a
<em>sound cone</em> representing how directional the sound is. For
example, the sound could be omnidirectional, in which case it would
be heard anywhere regardless of its orientation, or it can be more
directional and heard only if it is facing the listener.
{{AudioListener}} objects (representing a person's
ears) have [=forward=] and [=up=] vectors
representing in which direction the person is facing.

The coordinate system for spatialization is shown in the diagram
below, with the default values shown.  The locations for the
{{AudioListener}} and {{PannerNode}} are moved from the default
positions so we can see things better.

<figure>
    <img alt="panner-coord" src="images/panner-coord.svg">
    <figcaption>
        Diagram of the coordinate system with AudioListener
        and PannerNode attributes shown.
    </figcaption>
</figure>

During rendering, the {{PannerNode}} calculates an
<em>azimuth</em> and <em>elevation</em>. These values are used
internally by the implementation in order to render the
spatialization effect. See the <a href="#Spatialization-panning-algorithm">Panning Algorithm</a> section for
details of how these values are used.

<h3 id="azimuth-elevation">
Azimuth and Elevation</h3>

The following algorithm MUST be used to calculate the
<em>azimuth</em> and <em>elevation</em> for the
{{PannerNode}}.  The implementation must appropriately account for whether the various {{AudioParam}}s below are "{{AutomationRate/a-rate}}" or "{{AutomationRate/k-rate}}".

<xmp highlight="js" line-numbers>
// Let |context| be a BaseAudioContext and let |panner| be a
// PannerNode created in |context|.

// Calculate the source-listener vector.
const listener = context.listener;
const sourcePosition = new Vec3(panner.positionX.value, panner.positionY.value,
                                panner.positionZ.value);
const listenerPosition =
    new Vec3(listener.positionX.value, listener.positionY.value,
             listener.positionZ.value);
const sourceListener = sourcePosition.diff(listenerPosition).normalize();

if (sourceListener.magnitude == 0) {
  // Handle degenerate case if source and listener are at the same point.
  azimuth = 0;
  elevation = 0;
  return;
}

// Align axes.
const listenerForward = new Vec3(listener.forwardX.value, listener.forwardY.value,
                                 listener.forwardZ.value);
const listenerUp =
    new Vec3(listener.upX.value, listener.upY.value, listener.upZ.value);
const listenerRight = listenerForward.cross(listenerUp);

if (listenerRight.magnitude == 0) {
  // Handle the case where listener's 'up' and 'forward' vectors are linearly
  // dependent, in which case 'right' cannot be determined
  azimuth = 0;
  elevation = 0;
  return;
}

// Determine a unit vector orthogonal to listener's right, forward
const listenerRightNorm = listenerRight.normalize();
const listenerForwardNorm = listenerForward.normalize();
const up = listenerRightNorm.cross(listenerForwardNorm);

const upProjection = sourceListener.dot(up);
const projectedSource = sourceListener.diff(up.scale(upProjection)).normalize();

azimuth = 180 * Math.acos(projectedSource.dot(listenerRightNorm)) / Math.PI;

// Source in front or behind the listener.
const frontBack = projectedSource.dot(listenerForwardNorm);
if (frontBack < 0)
  azimuth = 360 - azimuth;

// Make azimuth relative to "forward" and not "right" listener vector.
if ((azimuth >= 0) && (azimuth <= 270))
  azimuth = 90 - azimuth;
else
  azimuth = 450 - azimuth;

elevation = 90 - 180 * Math.acos(sourceListener.dot(up)) / Math.PI;

if (elevation > 90)
  elevation = 180 - elevation;
else if (elevation < -90)
  elevation = -180 - elevation;
</xmp>

<h3 id="Spatialization-panning-algorithm">
Panning Algorithm</h3>

<em>Mono-to-stereo</em> and <em>stereo-to-stereo</em> panning MUST be
supported. <em>Mono-to-stereo</em> processing is used when all
connections to the input are mono. Otherwise
<em>stereo-to-stereo</em> processing is used.

<h4 id="Spatialization-equal-power-panning">
PannerNode "equalpower" Panning</h4>

This is a simple and relatively inexpensive algorithm which
provides basic, but reasonable results. It is used for the
{{PannerNode}} when the {{PannerNode/panningModel}} attribute is set to
"{{PanningModelType/equalpower}}", in which case the <em>elevation</em>
value is ignored. This algorithm MUST be implemented using
the appropriate rate as specified by the
{{AudioParam/automationRate}}.  If any of the {{PannerNode}}'s
{{AudioParam}}s or the {{AudioListener}}'s {{AudioParam}}s are
"{{AutomationRate/a-rate}}", <a>a-rate</a> processing must be used.

<div algorithm="equalpower panning">
    1. For each sample to be computed by this {{AudioNode}}:

        1. Let <var>azimuth</var> be the value computed in the <a href="#azimuth-elevation">azimuth and elevation</a> section.

        2. The <var>azimuth</var> value is first contained to be within
            the range [-90, 90] according to:

            <pre highlight="js">
            // First, clamp azimuth to allowed range of [-180, 180].
            azimuth = max(-180, azimuth);
            azimuth = min(180, azimuth);

            // Then wrap to range [-90, 90].
            if (azimuth &lt; -90)
                azimuth = -180 - azimuth;
            else if (azimuth &gt; 90)
                azimuth = 180 - azimuth;
            </pre>

        3. A normalized value <em>x</em> is calculated from
            <var>azimuth</var> for a mono input as:

            <pre highlight="js">
            x = (azimuth + 90) / 180;
            </pre>

            Or for a stereo input as:

            <pre highlight="js">
            if (azimuth &lt;= 0) { // -90 -&gt; 0
                // Transform the azimuth value from [-90, 0] degrees into the range [-90, 90].
                x = (azimuth + 90) / 90;
            } else { // 0 -&gt; 90
                // Transform the azimuth value from [0, 90] degrees into the range [-90, 90].
                x = azimuth / 90;
            }
            </pre>

        4. Left and right gain values are calculated as:

            <pre highlight="js">
            gainL = cos(x * Math.PI / 2);
            gainR = sin(x * Math.PI / 2);
            </pre>

        5. For mono input, the stereo output is calculated as:

            <pre highlight="js">
            outputL = input * gainL;
            outputR = input * gainR;
            </pre>

            Else for stereo input, the output is calculated as:

            <pre highlight="js">
            if (azimuth &lt;= 0) {
                outputL = inputL + inputR * gainL;
                outputR = inputR * gainR;
            } else {
                outputL = inputL * gainL;
                outputR = inputR + inputL * gainR;
            }
            </pre>
        6. Apply the distance gain and cone gain where the
            computation of the distance is described in
            [[#Spatialization-distance-effects|Distance
            Effects]] and the cone gain is described in
            [[#Spatialization-sound-cones|Sound Cones]]:

            <pre highlight="js">
            let distance = distance();
            let distanceGain = distanceModel(distance);
            let totalGain = coneGain() * distanceGain();
            outputL = totalGain * outputL;
            outputR = totalGain * outputR;
            </pre>

</div>

<h4 id="Spatialization-hrtf-panning">
PannerNode "HRTF" Panning (Stereo Only)</h4>

This requires a set of <a href="https://en.wikipedia.org/wiki/Head-related_transfer_function">HRTF</a>
(Head-related Transfer Function) impulse responses recorded at a
variety of azimuths and elevations. The implementation requires a
highly optimized convolution function. It is somewhat more costly
than "equalpower", but provides more perceptually spatialized
sound.

<figure>
    <img alt="" src="images/HRTF_panner.png" width="644"
    height="419">
    <figcaption>
        A diagram showing the process of panning a source using HRTF.
    </figcaption>
</figure>

<h4 id="stereopanner-algorithm">
StereoPannerNode Panning</h4>

<div algorithm="pan a StereoPannerNode">
    For a {{StereoPannerNode}}, the following algorithm
    MUST be implemented.

    1. For each sample to be computed by this {{AudioNode}}
        1. Let <var>pan</var> be the <a>computedValue</a> of the
            <code>pan</code> {{AudioParam}} of this
            {{StereoPannerNode}}.

        2. Clamp <var>pan</var> to [-1, 1].

            <pre highlight="js">
            pan = max(-1, pan);
            pan = min(1, pan);
            </pre>

        3. Calculate <em>x</em> by normalizing <var>pan</var> value to
            [0, 1]. For mono input:

            <pre highlight="js">
            x = (pan + 1) / 2;
            </pre>

            For stereo input:

            <pre highlight="js">
            if (pan &lt;= 0)
                x = pan + 1;
            else
                x = pan;
            </pre>

        4. Left and right gain values are calculated as:

            <pre highlight="js">
            gainL = cos(x * Math.PI / 2);
            gainR = sin(x * Math.PI / 2);
            </pre>

        5. For mono input, the stereo output is calculated as:

            <pre highlight="js">
            outputL = input * gainL;
            outputR = input * gainR;
            </pre>

            Else for stereo input, the output is calculated as:

            <pre highlight="js">
            if (pan &lt;= 0) {
                outputL = inputL + inputR * gainL;
                outputR = inputR * gainR;
            } else {
                outputL = inputL * gainL;
                outputR = inputR + inputL * gainR;
            }
            </pre>
</div>

<h3 id="Spatialization-distance-effects">
Distance Effects</h3>

Sounds which are closer are louder, while sounds further away are
quieter. Exactly <em>how</em> a sound's volume changes according to
distance from the listener depends on the {{PannerNode/distanceModel}}
attribute.

During audio rendering, a <em>distance</em> value will be calculated
based on the panner and listener positions according to:

<xmp highlight="js" line-numbers>
function distance(panner) {
  const pannerPosition = new Vec3(panner.positionX.value, panner.positionY.value,
                                  panner.positionZ.value);
  const listener = context.listener;
  const listenerPosition =
      new Vec3(listener.positionX.value, listener.positionY.value,
               listener.positionZ.value);
  return pannerPosition.diff(listenerPosition).magnitude;
}
</xmp>

<em>distance</em> will then be used to calculate
<em>distanceGain</em> which depends on the {{PannerNode/distanceModel}}
attribute. See the {{DistanceModelType}} section for details of how
this is calculated for each distance model.

As part of its processing, the {{PannerNode}}
scales/multiplies the input audio signal by <em>distanceGain</em> to
make distant sounds quieter and nearer ones louder.


<h3 id="Spatialization-sound-cones">
Sound Cones</h3>

The listener and each sound source have an orientation vector
describing which way they are facing. Each sound source's sound
projection characteristics are described by an inner and outer "cone"
describing the sound intensity as a function of the source/listener
angle from the source's orientation vector. Thus, a sound source
pointing directly at the listener will be louder than if it is
pointed off-axis. Sound sources can also be omni-directional.

The following diagram ilustrates the relationship between the source's
cone with respect to the listener.  In the diagram,
<code>{{PannerNode/coneInnerAngle}} = 50</code> and
<code>{{PannerNode/coneOuterAngle}} = 120</code>.  That
is, the inner cone extends 25 deg on each side of the direction
vector.  Similarly, the outer cone is 60 deg on each side.

<figure>
    <img alt="cone-diagram" src="images/cone-diagram.svg">
    <figcaption>
        Cone angles for a source in relationship to the source orientation and the listeners position and orientation.
    </figcaption>
</figure>

The following algorithm MUST be used to calculate the gain
contribution due to the cone effect, given the source (the
{{PannerNode}}) and the listener:

<xmp highlight="js" line-numbers>
function coneGain() {
  const sourceOrientation =
      new Vec3(source.orientationX, source.orientationY, source.orientationZ);
  if (sourceOrientation.magnitude == 0 ||
      ((source.coneInnerAngle == 360) && (source.coneOuterAngle == 360)))
    return 1; // no cone specified - unity gain

  // Normalized source-listener vector
  const sourcePosition = new Vec3(panner.positionX.value, panner.positionY.value,
                                  panner.positionZ.value);
  const listenerPosition =
      new Vec3(listener.positionX.value, listener.positionY.value,
               listener.positionZ.value);
  const sourceToListener = sourcePosition.diff(listenerPosition).normalize();

  const normalizedSourceOrientation = sourceOrientation.normalize();

  // Angle between the source orientation vector and the source-listener vector
  const angle = 180 *
                Math.acos(sourceToListener.dot(normalizedSourceOrientation)) /
                Math.PI;
  const absAngle = Math.abs(angle);

  // Divide by 2 here since API is entire angle (not half-angle)
  const absInnerAngle = Math.abs(source.coneInnerAngle) / 2;
  const absOuterAngle = Math.abs(source.coneOuterAngle) / 2;
  let gain = 1;

  if (absAngle <= absInnerAngle) {
    // No attenuation
    gain = 1;
  } else if (absAngle >= absOuterAngle) {
    // Max attenuation
    gain = source.coneOuterGain;
  } else {
    // Between inner and outer cones
    // inner -> outer, x goes from 0 -> 1
    const x = (absAngle - absInnerAngle) / (absOuterAngle - absInnerAngle);
    gain = (1 - x) + source.coneOuterGain * x;
  }

  return gain;
}
</xmp>


<!-- Big Text: Perf -->

<h2 id="Performance">
Performance Considerations</h2>

<h3 id="latency">
Latency</h3>

<figure>
    <img alt="latency" src="images/latency.png" width="700" height="201">
    <figcaption>
        Use cases in which the latency can be important
    </figcaption>
</figure>

For web applications, the time delay between mouse and keyboard
events (keydown, mousedown, etc.) and a sound being heard is
important.

This time delay is called latency and is caused by several factors
(input device latency, internal buffering latency, DSP processing
latency, output device latency, distance of user's ears from
speakers, etc.), and is cumulative. The larger this latency is, the
less satisfying the user's experience is going to be. In the extreme,
it can make musical production or game-play impossible. At moderate
levels it can affect timing and give the impression of sounds lagging
behind or the game being non-responsive. For musical applications the
timing problems affect rhythm. For gaming, the timing problems affect
precision of gameplay. For interactive applications, it generally
cheapens the users experience much in the same way that very low
animation frame-rates do. Depending on the application, a reasonable
latency can be from as low as 3-6 milliseconds to 25-50 milliseconds.

Implementations will generally seek to minimize overall latency.

Along with minimizing overall latency, implementations will generally
seek to minimize the difference between an
{{AudioContext}}'s <code>currentTime</code> and an
{{AudioProcessingEvent}}'s <code>playbackTime</code>.
Deprecation of {{ScriptProcessorNode}} will make this
consideration less important over time.

Additionally, some {{AudioNode}}s can add latency to some paths
of the audio graph, notably:

* The {{AudioWorkletNode}} can run a script that buffers
    internally, adding delay to the signal path.

* The {{DelayNode}}, whose role is to add controlled latency
    time.

* The {{BiquadFilterNode}} and {{IIRFilterNode}} filter
    design can delay incoming samples, as a natural consequence of the
    causal filtering process.

* The {{ConvolverNode}} depending on the impulse, can delay
    incoming samples, as a natural result of the convolution operation.

* The {{DynamicsCompressorNode}} has a look ahead algorithm that
    causes delay in the signal path.

* The {{MediaStreamAudioSourceNode}},
    {{MediaStreamTrackAudioSourceNode}} and
    {{MediaStreamAudioDestinationNode}}, depending on the
    implementation, can add buffers internally that add delays.

* The {{ScriptProcessorNode}} can have buffers between the
    control thread and the rendering thread.

* The {{WaveShaperNode}}, when oversampling, and depending on
    the oversampling technique, add delays to the signal path.

<h3 id="audio-buffer-copying">
Audio Buffer Copying</h3>

When an <a href="#acquire-the-content">acquire the content</a>
operation is performed on an {{AudioBuffer}}, the entire operation
can usually be implemented without copying channel data. In
particular, the last step SHOULD be performed lazily at the next
{{AudioBuffer/getChannelData()}} call.
That means a sequence of consecutive <a href="#acquire-the-content">acquire the contents</a> operations with no
intervening {{AudioBuffer/getChannelData()}} (e.g. multiple
{{AudioBufferSourceNode}}s playing the same
{{AudioBuffer}}) can be implemented with no
allocations or copying.

Implementations can perform an additional optimization: if
{{AudioBuffer/getChannelData()}} is called on an
{{AudioBuffer}}, fresh {{ArrayBuffer}}s have not yet been
allocated, but all invokers of previous <a href="#acquire-the-content">acquire the content</a> operations on an
{{AudioBuffer}} have stopped using the {{AudioBuffer}}'s data,
the raw data buffers can be recycled for use with new
{{AudioBuffer}}s, avoiding any reallocation or copying of the
channel data.

<h3 id="audioparam-transitions">
AudioParam Transitions</h3>

While no automatic smoothing is done when directly setting the
{{AudioParam/value}} attribute of an
{{AudioParam}}, for certain parameters, smooth
transition are preferable to directly setting the value.

Using the {{AudioParam/setTargetAtTime()}} method with a low
<code>timeConstant</code> allows authors to perform a smooth
transition.

<h3 id="audio-glitching">
Audio Glitching</h3>

Audio glitches are caused by an interruption of the normal continuous
audio stream, resulting in loud clicks and pops. It is considered to
be a catastrophic failure of a multi-media system and MUST be
avoided. It can be caused by problems with the threads responsible
for delivering the audio stream to the hardware, such as scheduling
latencies caused by threads not having the proper priority and
time-constraints. It can also be caused by the audio DSP trying to do
more work than is possible in real-time given the CPU's speed.


<!-- Big Text: priv-sec -->

<h2 id="priv-sec">
Security and Privacy Considerations</h2>

Per the [[security-privacy-questionnaire#questions]]:

1. Does this specification deal with personally-identifiable information?

    It would be possible to perform a hearing test using Web Audio API, thus
    revealing the range of frequencies audible to a person (this decreases
    with age). It is difficult to see how this could be done without the
    realization and consent of the user, as it requires active particpation.
    <!-- assuming the audio context does not expose detailed information
    on audio device inputs and outputs; revisit this question after the
    fingerprinting analysis is done -->


2. Does this specification deal with high-value data?

    No. Credit card information and the like is not used in Web Audio.
    It is possible to use Web Audio to process or analyze voice data,
    which might be a privacy concern, but access to the user's
    microphone is permission-based via {{getUserMedia()}}.

3. Does this specification introduce new state for an origin that
    persists across browsing sessions?

    No. AudioWorklet does not persist across browsing sessions.

4. Does this specification expose persistent, cross-origin state to
    the web?

    Yes, the supported audio sample rate(s) and the output device channel count are exposed. See {{AudioContext}}.

5. Does this specification expose any other data to an origin that it
    doesn’t currently have access to?

    Yes. When giving various information on available
    {{AudioNode}}s, the Web Audio API potentially
    exposes information on characteristic features of the client (such
    as audio hardware sample-rate) to any page that makes use of the
    {{AudioNode}} interface. Additionally, timing
    information can be collected through the
    {{AnalyserNode}} or
    {{ScriptProcessorNode}} interface. The information
    could subsequently be used to create a fingerprint of the client.

    Research by Princeton CITP's <a href="https://audiofingerprint.openwpm.com/">
    Web Transparency and Accountability Project</a>
    has shown that {{DynamicsCompressorNode}} and {{OscillatorNode}} can
    be used to gather entropy from a client to fingerprint a device.
    This is due to small, and normally inaudible, differences in DSP
    architecture, resampling strategies and rounding trade-offs between
    differing implementations. The precise compiler flags used and also the
    CPU architecture (ARM vs. x86) contribute to this entropy.

    In practice however, this merely allows deduction of information
    already readily available by easier means (User Agent string),
    such as "this is browser X running on platform Y".  However, to reduce the
    possibility of additional fingerprinting, we mandate browsers take
    action to mitigate fingerprinting issues that might be possible from the
    output of any node.

    Fingerprinting via clock skew
    <a href="https://murdoch.is/talks/eurobsdcon07hotornot.pdf">has
    been described by Steven J Murdoch and Sebastian Zander</a>. It might be possible
    to determine this from {{getOutputTimestamp}}. Skew-based fingerprinting has also
    been demonstrated
    <a href="https://pdfs.semanticscholar.org/cfd2/6a17234696593919df3f880a235d6ac5871d.pdf">
    by Nakibly et. al. for HTML</a>. The [[hr-time-3#sec-privacy]] section should be consulted for further
    information on clock resolution and drift.

    Fingerprinting via latency is also possible; it might be possible to deduce this
    from {{baseLatency}} and {{outputLatency}}. Mitigation
    strategies include adding jitter (dithering) and quantization so that the exact
    skew is incorrectly reported. Note however that most audio systems aim
    for <a href="https://padenot.github.io/web-audio-perf/#latency">low latency</a>,
    to synchronise the audio generated by WebAudio to other
    audio or video sources or to visual cues (for example in a game, or an audio
    recording or music making environment). Excessive latency decreases usability and may be
    an accessibility issue.

    Fingerprining via the sample rate of the {{AudioContext}} is also possible.  We
    recommend the following steps to be taken to minimize this:

    1. 44.1 kHz and 48 kHz are allowed as default rates; the system will choose
        between them for best applicability. (Obviously, if the audio device is
        natively 44.1, 44.1 will be chosen, etc., but also the system may choose
        the most "compatible" rate&mdash;e.g. if the system is natively 96kHz,
        48kHz would likely be chosen, not 44.1kHz.
    1. The system should resample to one of those two rates for devices that are
        natively at different rates, despite the fact that this may cause extra
        battery drain due to resampled audio. (Again, the system will choose the
        most compatible rate&mdash;e.g. if the native system is 16kHz, it's
        expected that 48kHz would be chosen.)
    1. It is expected (though not mandated) that browsers would offer a user
        affordance to force use of the native rate&mdash;e.g. by setting a flag in
        the browser on the device. This setting would not be exposed in the API.
    1. It is also expected behavior that a different rate could be explicitly
        requested in the constructor for {{AudioContext}} (this is already in the
        specification; it normally causes the audio rendering to be done at the
        requested sampleRate, and then up- or down-sampled to the device output),
        and if that rate is natively supported, the rendering could be passed
        straight through. This would enable apps to render to higher rates without
        user intervention (although it's not observable from Web Audio that the
        audio output is not downsampled on output)&mdash;for example, if
        {{MediaDevices}} capabilities were read (with user intervention) and indicated
        a higher rate was supported.

    Fingerprinting via the number of output channels for the
    {{AudioContext}} is possible as well.  We recommend that
    {{AudioDestinationNode/maxChannelCount}} be set to two
    (stereo).  Stereo is by far the most common number of
    channels.

6. Does this specification enable new script execution/loading
    mechanisms?

    No. It does use the [[HTML]] script execution method,
    defined in that specification.

7. Does this specification allow an origin access to a user’s
    location?

    No.

8. Does this specification allow an origin access to sensors on a
    user’s device?

    Not directly. Currently, audio input is not specified in this
    document, but it will involve gaining access to the client
    machine's audio input or microphone. This will require asking the
    user for permission in an appropriate way, probably via the
    {{getUserMedia()}} API.
    
    Additionally, the security and privacy considerations from the 
    <a href="https://www.w3.org/TR/mediacapture-streams/">Media Capture 
    and Streams</a> specification should be noted. In particular, 
    analysis of ambient audio or playing unique audio may enable 
    identification of user location down to the level of a room or 
    even simultaneous occupation of a room by disparate users or 
    devices. Access to both audio output and audio input might also
    enable communication between otherwise partitioned contexts in one 
    browser.

9. Does this specification allow an origin access to aspects of a
    user’s local computing environment?

<!-- from f2f -->
    Not directly; all requested sample rates are supported, with upsampling if needed.
    It is possible to use Media Capture and Streams to
    probe for supported audio sample rates with
    <a href="https://www.w3.org/TR/mediacapture-streams/#media-track-supported-constraints">MediaTrackSupportedConstraints</a>.
    This requires explicit user consent.
    This does provide a small measure of fingerprinting. However,
    in practice most consumer and prosumer devices use one of two
    standardized sample rates: 44.1kHz (originally used by CD) and 48kHz
    (originally used by DAT). Highly resource constrained devices may
    support the speech-quality 11kHz sample rate, and higher-end devices often
    support 88.2, 96, or even the audiophile 192kHz rate.

    Requiring all implementations to upsample to a single, commonly-supported
    rate such as 48kHz would increase CPU cost for no particular benefit, and
    requiring higher-end devices to use a lower rate would merely result in
    Web Audio being labelled as unsuitable for professional use.

10. Does this specification allow an origin access to other devices?

    It typically does not allow access to other networked devices (an
    exception in a high-end recording studio might be Dante networked
    devices, although these typically use a separate, dedicated network).
    It does of necessity allow access to the user's audio output device
    or devices, which are sometimes separate units to the computer.

    For voice or sound-actuated devices, Web Audio API <em>might</em> be used
    to control other devices. In addition, if the sound-operated device is sensitive
    to near ultrasonic frequencies, such control might not be audible.
    This possibility also exists with HTML, through either
    the &lt;audio&gt; or &lt;video&gt; element. At common audio sampling rates, there is (by design)
    insufficient headroom for much ultrasonic information:

    The limit of human hearing is usually stated as 20kHz. For a 44.1kHz
    sampling rate, the Nyquist limit is 22.05kHz. Given that a true
    brickwall filter cannot be physically realized, the space between
    20kHz and 22.05kHz is used for a rapid rolloff filter to strongly
    attenuate all frequencies above Nyquist.

    At 48kHz sampling rate, there is still rapid attenuation in the
    20kHz to 24kHz band (but it is easier to avoid phase ripple
    errors in the passband).

11. Does this specification allow an origin some measure of control
    over a user agent’s native UI?

    If the UI has audio components, such as a voice assistant or screenreader,
    Web Audio API might be used to emulate aspects of the native UI to make
    an attack seem more like a local system event.
    This possibility also exists with HTML, through
    the &lt;audio&gt; element.

12. Does this specification expose temporary identifiers to the web?

    No.

13. Does this specification distinguish between behavior in first-party
    and third-party contexts?

    No.

14. How should this specification work in the context of a user agent’s
    "incognito" mode?

    Not differently.

15. Does this specification persist data to a user’s local device?

    No.

16. Does this specification have a "Security Considerations" and
    "Privacy Considerations" section?

    Yes (you are reading it).

17. Does this specification allow downgrading default security
    characteristics?

    No.

<h2 id="requirements">
Requirements and Use Cases</h2>

Please see [[webaudio-usecases]].


<h2 id="common-definitions">
Common Definitions for Specification Code</h2>

This section describes common functions and classes employed by
JavaScript code used within this specification.

<pre highlight="js" line-numbers>
// Three dimensional vector class.
class Vec3 {
    // Construct from 3 coordinates.
    constructor(x, y, z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    // Dot product with another vector.
    dot(v) {
        return (this.x * v.x) + (this.y * v.y) + (this.z * v.z);
    }

    // Cross product with another vector.
    cross(v) {
        return new Vec3((this.y * v.z) - (this.z * v.y),
            (this.z * v.x) - (this.x * v.z),
            (this.x * v.y) - (this.y * v.x));
    }

    // Difference with another vector.
    diff(v) {
        return new Vec3(this.x - v.x, this.y - v.y, this.z - v.z);
    }

    // Get the magnitude of this vector.
    get magnitude() {
        return Math.sqrt(dot(this));
    }

    // Get a copy of this vector multiplied by a scalar.
    scale(s) {
        return new Vec3(this.x * s, this.y * s, this.z * s);
    }

    // Get a normalized copy of this vector.
    normalize() {
        const m = magnitude;
        if (m == 0) {
            return new Vec3(0, 0, 0);
        }
        return scale(1 / m);
    }
}
</pre>

<h2 id="changes">
Change Log</h2>

<h2 id="acks">
Acknowledgements</h2>

This specification is the collective work of the W3C <a href="http://www.w3.org/2011/audio/">Audio Working Group</a>.

Members and former members of the Working Group and contributors to the specification are (at the time of writing, and by
alphabetical order):<br>
Adenot, Paul (Mozilla Foundation) - Specification Co-editor;
Akhgari, Ehsan (Mozilla Foundation);
Becker, Steven (Microsoft Corporation);
Berkovitz, Joe (Invited Expert, affiliated with Noteflight/Hal Leonard) - WG co-chair from September 2013 to December 2017);
Bossart, Pierre (Intel Corporation);
Borins, Myles (Google, Inc);
Buffa, Michel (NSAU);
Caceres, Marcos (Invited Expert);
Cardoso, Gabriel (INRIA);
Carlson, Eric (Apple, Inc);
Chen, Bin (Baidu, Inc);
Choi, Hongchan (Google, Inc) - Specification Co-editor;
Collichio, Lisa (Qualcomm);
Geelnard, Marcus (Opera Software);
Gehring, Todd (Dolby Laboratories);
Goode, Adam (Google, Inc);
Gregan, Matthew (Mozilla Foundation);
Hikawa, Kazuo (AMEI);
Hofmann, Bill (Dolby Laboratories);
Jägenstedt, Philip (Google, Inc);
Jeong, Paul Changjin (HTML5 Converged Technology Forum);
Kalliokoski, Jussi (Invited Expert);
Lee, WonSuk (Electronics and Telecommunications Research Institute);
Kakishita, Masahiro (AMEI);
Kawai, Ryoya (AMEI);
Kostiainen, Anssi (Intel Corporation);
Lilley, Chris (W3C Staff);
Lowis, Chris (Invited Expert) - WG co-chair from December 2012 to September 2013, affiliated with British Broadcasting Corporation;
MacDonald, Alistair (W3C Invited Experts) — WG co-chair from March 2011 to July 2012;
Mandyam, Giridhar (Qualcomm Innovation Center, Inc);
Michel, Thierry (W3C/ERCIM);
Nair, Varun (Facebook);
Needham, Chris (British Broadcasting Corporation);
Noble, Jer (Apple, Inc);
O'Callahan, Robert(Mozilla Foundation);
Onumonu, Anthony (British Broadcasting Corporation);
Paradis, Matthew (British Broadcasting Corporation) - WG co-chair from September 2013 to present;
Pozdnyakov, Mikhail (Intel Corporation);
Raman, T.V. (Google, Inc);
Rogers, Chris (Google, Inc);
Schepers, Doug (W3C/MIT);
Schmitz, Alexander (JS Foundation);
Shires, Glen (Google, Inc);
Smith, Jerry (Microsoft Corporation);
Smith, Michael (W3C/Keio);
Thereaux, Olivier (British Broadcasting Corporation);
Toy, Raymond (Google, Inc.) - WG co-chair from December 2017 - Present;
Toyoshima, Takashi (Google, Inc);
Troncy, Raphael (Institut Telecom);
Verdie, Jean-Charles (MStar Semiconductor, Inc.);
Wei, James (Intel Corporation);
Weitnauer, Michael (IRT);
Wilson, Chris (Google,Inc);
Zergaoui, Mohamed (INNOVIMAX)
